diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/viewers/StructuredViewerProvisioningListener.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/viewers/StructuredViewerProvisioningListener.java
index 0dfad8a60..6245d5e77 100644
--- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/viewers/StructuredViewerProvisioningListener.java
+++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/p2/ui/viewers/StructuredViewerProvisioningListener.java
@@ -1,93 +1,97 @@
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.p2.ui.viewers;
import java.util.EventObject;
import org.eclipse.equinox.internal.p2.ui.IProvisioningListener;
import org.eclipse.equinox.p2.core.eventbus.SynchronousProvisioningListener;
import org.eclipse.equinox.p2.engine.ProfileEvent;
import org.eclipse.equinox.p2.ui.model.ProfileElement;
import org.eclipse.equinox.p2.ui.query.IQueryProvider;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.widgets.Display;
/**
* ProvisioningListener which updates a structured viewer based on
* provisioning changes
*
* @since 3.4
*/
public class StructuredViewerProvisioningListener implements SynchronousProvisioningListener, IProvisioningListener {
public static final int PROV_EVENT_REPOSITORY = 0x0001;
public static final int PROV_EVENT_IU = 0x0002;
public static final int PROV_EVENT_PROFILE = 0x0004;
int eventTypes = 0;
StructuredViewer viewer;
Display display;
IQueryProvider queryProvider;
public StructuredViewerProvisioningListener(StructuredViewer viewer, int eventTypes, IQueryProvider queryProvider) {
this.viewer = viewer;
this.eventTypes = eventTypes;
this.display = viewer.getControl().getDisplay();
this.queryProvider = queryProvider;
}
public void notify(EventObject o) {
if (o instanceof ProfileEvent && (((eventTypes & PROV_EVENT_IU) == PROV_EVENT_IU) || ((eventTypes & PROV_EVENT_PROFILE) == PROV_EVENT_PROFILE))) {
ProfileEvent event = (ProfileEvent) o;
if (event.getReason() == ProfileEvent.CHANGED) {
final String profileId = event.getProfileId();
display.asyncExec(new Runnable() {
public void run() {
+ if (viewer.getControl().isDisposed())
+ return;
// We want to refresh the affected profile, so we
// construct a profile element on this profile.
ProfileElement element = new ProfileElement(profileId);
element.setQueryProvider(queryProvider);
viewer.refresh(element);
}
});
} else {
display.asyncExec(new Runnable() {
public void run() {
+ if (viewer.getControl().isDisposed())
+ return;
refreshAll();
}
});
}
} else if ((o.getSource() instanceof String) && (eventTypes & PROV_EVENT_REPOSITORY) == PROV_EVENT_REPOSITORY) {
String name = (String) o.getSource();
if (name.equals(IProvisioningListener.REPO_ADDED) || (name.equals(IProvisioningListener.REPO_REMOVED))) {
display.asyncExec(new Runnable() {
public void run() {
refreshAll();
}
});
}
}
}
/**
* Refresh the entire structure of the viewer. Subclasses may
* override to ensure that any caching of content providers or
* model elements is refreshed before the viewer is refreshed.
*/
protected void refreshAll() {
viewer.refresh();
}
public int getEventTypes() {
return eventTypes;
}
}
| false | true | public void notify(EventObject o) {
if (o instanceof ProfileEvent && (((eventTypes & PROV_EVENT_IU) == PROV_EVENT_IU) || ((eventTypes & PROV_EVENT_PROFILE) == PROV_EVENT_PROFILE))) {
ProfileEvent event = (ProfileEvent) o;
if (event.getReason() == ProfileEvent.CHANGED) {
final String profileId = event.getProfileId();
display.asyncExec(new Runnable() {
public void run() {
// We want to refresh the affected profile, so we
// construct a profile element on this profile.
ProfileElement element = new ProfileElement(profileId);
element.setQueryProvider(queryProvider);
viewer.refresh(element);
}
});
} else {
display.asyncExec(new Runnable() {
public void run() {
refreshAll();
}
});
}
} else if ((o.getSource() instanceof String) && (eventTypes & PROV_EVENT_REPOSITORY) == PROV_EVENT_REPOSITORY) {
String name = (String) o.getSource();
if (name.equals(IProvisioningListener.REPO_ADDED) || (name.equals(IProvisioningListener.REPO_REMOVED))) {
display.asyncExec(new Runnable() {
public void run() {
refreshAll();
}
});
}
}
}
| public void notify(EventObject o) {
if (o instanceof ProfileEvent && (((eventTypes & PROV_EVENT_IU) == PROV_EVENT_IU) || ((eventTypes & PROV_EVENT_PROFILE) == PROV_EVENT_PROFILE))) {
ProfileEvent event = (ProfileEvent) o;
if (event.getReason() == ProfileEvent.CHANGED) {
final String profileId = event.getProfileId();
display.asyncExec(new Runnable() {
public void run() {
if (viewer.getControl().isDisposed())
return;
// We want to refresh the affected profile, so we
// construct a profile element on this profile.
ProfileElement element = new ProfileElement(profileId);
element.setQueryProvider(queryProvider);
viewer.refresh(element);
}
});
} else {
display.asyncExec(new Runnable() {
public void run() {
if (viewer.getControl().isDisposed())
return;
refreshAll();
}
});
}
} else if ((o.getSource() instanceof String) && (eventTypes & PROV_EVENT_REPOSITORY) == PROV_EVENT_REPOSITORY) {
String name = (String) o.getSource();
if (name.equals(IProvisioningListener.REPO_ADDED) || (name.equals(IProvisioningListener.REPO_REMOVED))) {
display.asyncExec(new Runnable() {
public void run() {
refreshAll();
}
});
}
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java
index cfe297641..95bdef009 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/CVSSyncInfo.java
@@ -1,371 +1,371 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.core;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.subscribers.*;
import org.eclipse.team.core.synchronize.*;
import org.eclipse.team.core.variants.*;
import org.eclipse.team.core.variants.ResourceVariantTreeSubscriber;
import org.eclipse.team.internal.ccvs.core.client.Update;
import org.eclipse.team.internal.ccvs.core.resources.*;
import org.eclipse.team.internal.ccvs.core.syncinfo.*;
import org.eclipse.team.internal.ccvs.core.util.Assert;
import org.eclipse.team.internal.ccvs.core.Policy;
/**
* CVSSyncInfo
*/
public class CVSSyncInfo extends SyncInfo {
/*
* Codes that are used in returned IStatus
*/
private static final int INVALID_RESOURCE_TYPE = 1;
private static final int INVALID_SYNC_KIND = 2;
private static final int PARENT_NOT_MANAGED = 3;
private static final int REMOTE_DOES_NOT_EXIST = 4;
private static final int SYNC_INFO_CONFLICTS = 5;
private Subscriber subscriber;
public CVSSyncInfo(IResource local, IResourceVariant base, IResourceVariant remote, Subscriber subscriber) {
super(local, base, remote, ((ResourceVariantTreeSubscriber)subscriber).getResourceComparator());
this.subscriber = subscriber;
}
public Subscriber getSubscriber() {
return subscriber;
}
/* (non-Javadoc)
* @see org.eclipse.team.core.sync.SyncInfo#computeSyncKind(org.eclipse.core.runtime.IProgressMonitor)
*/
protected int calculateKind() throws TeamException {
// special handling for folders, the generic sync algorithm doesn't work well
// with CVS because folders are not in namespaces (e.g. they exist in all versions
// and branches).
IResource local = getLocal();
if(local.getType() != IResource.FILE) {
int folderKind = SyncInfo.IN_SYNC;
ICVSRemoteFolder remote = (ICVSRemoteFolder)getRemote();
ICVSFolder cvsFolder = CVSWorkspaceRoot.getCVSFolderFor((IContainer)local);
boolean isCVSFolder = false;
try {
isCVSFolder = cvsFolder.isCVSFolder();
} catch (CVSException e) {
// Assume the folder is not a CVS folder
}
if(!local.exists()) {
if(remote != null) {
if (isCVSFolder) {
// TODO: This assumes all CVS folders are in-sync even if they have been pruned!
folderKind = SyncInfo.IN_SYNC;
} else {
folderKind = SyncInfo.INCOMING | SyncInfo.ADDITION;
}
} else {
// ignore conflicting deletion to keep phantom sync info
}
} else {
if(remote == null) {
if(isCVSFolder) {
// TODO: This is not really an incoming deletion
// The folder will be pruned once any children are commited
folderKind = SyncInfo.IN_SYNC;
//folderKind = SyncInfo.INCOMING | SyncInfo.DELETION;
} else {
folderKind = SyncInfo.OUTGOING | SyncInfo.ADDITION;
}
} else if(!isCVSFolder) {
folderKind = SyncInfo.CONFLICTING | SyncInfo.ADDITION;
} else {
// folder exists both locally and remotely and are considered in sync, however
// we aren't checking the folder mappings to ensure that they are the same.
}
}
return folderKind;
}
// 1. Run the generic sync calculation algorithm, then handle CVS specific
// sync cases.
int kind = super.calculateKind();
// 2. Set the CVS specific sync type based on the workspace sync state provided
// by the CVS server.
IResourceVariant remote = getRemote();
if(remote!=null && (kind & SyncInfo.PSEUDO_CONFLICT) == 0) {
RemoteResource cvsRemote = (RemoteResource)remote;
int type = cvsRemote.getWorkspaceSyncState();
switch(type) {
// the server compared both text files and decided that it cannot merge
// them without line conflicts.
case Update.STATE_CONFLICT:
return kind | SyncInfo.MANUAL_CONFLICT;
// the server compared both text files and decided that it can safely merge
// them without line conflicts.
case Update.STATE_MERGEABLE_CONFLICT:
return kind | SyncInfo.AUTOMERGE_CONFLICT;
}
}
// 3. unmanage delete/delete conflicts and return that they are in sync
kind = handleDeletionConflicts(kind);
return kind;
}
/*
* If the resource has a delete/delete conflict then ensure that the local is unmanaged so that the
* sync info can be properly flushed.
*/
protected int handleDeletionConflicts(int kind) {
if(kind == (SyncInfo.CONFLICTING | SyncInfo.DELETION | SyncInfo.PSEUDO_CONFLICT)) {
try {
IResource local = getLocal();
ICVSResource cvsResource = CVSWorkspaceRoot.getCVSResourceFor(local);
if(!cvsResource.isFolder() && cvsResource.isManaged()) {
cvsResource.unmanage(null);
}
return SyncInfo.IN_SYNC;
} catch(CVSException e) {
CVSProviderPlugin.log(e);
return SyncInfo.CONFLICTING | SyncInfo.DELETION;
}
}
return kind;
}
/*
* Update the sync info of the local resource in such a way that the local changes can be committed.
* @return IStatus
* For folders, the makeInSYnc method is called and the return codes mentioned there apply
* for folders.
*/
public IStatus makeOutgoing(IProgressMonitor monitor) throws TeamException {
// For folders, there is no outgoing, only in-sync
if (getLocal().getType() == IResource.FOLDER) {
return makeInSync();
}
int syncKind = getKind();
boolean incoming = (syncKind & DIRECTION_MASK) == INCOMING;
boolean outgoing = (syncKind & DIRECTION_MASK) == OUTGOING;
ICVSResource local = CVSWorkspaceRoot.getCVSResourceFor(getLocal());
RemoteResource remote = (RemoteResource)getRemote();
ResourceSyncInfo origInfo = local.getSyncInfo();
MutableResourceSyncInfo info = null;
if(origInfo!=null) {
info = origInfo.cloneMutable();
}
if (outgoing) {
// The sync info is alright, it's already outgoing!
return Status.OK_STATUS;
} else if (incoming) {
// We have an incoming change, addition, or deletion that we want to ignore
if (local.exists()) {
// We could have an incoming change or deletion
if (remote == null) {
info.setAdded();
} else {
// Otherwise change the revision to the remote revision and dirty the file
info.setRevision(remote.getSyncInfo().getRevision());
info.setTimeStamp(null);
}
} else {
// We have an incoming add, turn it around as an outgoing delete
info = remote.getSyncInfo().cloneMutable();
info.setDeleted(true);
}
} else if (local.exists()) {
// We have a conflict and a local resource!
if (getRemote() != null) {
if (getBase() != null) {
// We have a conflicting change, Update the local revision
info.setRevision(remote.getSyncInfo().getRevision());
} else {
try {
// We have conflictin additions.
// We need to fetch the contents of the remote to get all the relevant information (timestamp, permissions)
// The most important thing we get is the keyword substitution mode which must be right to perform the commit
remote.getStorage(Policy.monitorFor(monitor)).getContents();
info = remote.getSyncInfo().cloneMutable();
} catch (CoreException e) {
- TeamException.asTeamException(e);
+ throw TeamException.asTeamException(e);
}
}
} else if (getBase() != null) {
// We have a remote deletion. Make the local an addition
info.setAdded();
} else {
// There's a local, no base and no remote. We can't possible have a conflict!
Assert.isTrue(false);
}
} else {
// We have a conflict and there is no local!
if (getRemote() != null) {
// We have a local deletion that conflicts with remote changes.
info.setRevision(remote.getSyncInfo().getRevision());
info.setDeleted(true);
} else {
// We have conflicting deletions. Clear the sync info
info = null;
return Status.OK_STATUS;
}
}
if(info!=null) {
FolderSyncInfo parentInfo = local.getParent().getFolderSyncInfo();
if (parentInfo == null) {
return new CVSStatus(IStatus.ERROR, PARENT_NOT_MANAGED, Policy.bind("CVSSyncInfo.9", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
info.setTag(parentInfo.getTag());
}
((ICVSFile)local).setSyncInfo(info, ICVSFile.UNKNOWN);
return Status.OK_STATUS;
}
/*
* Update the sync info of the local resource in such a way that the remote resource can be loaded
* ignore any local changes.
*/
public void makeIncoming(IProgressMonitor monitor) throws TeamException {
// To make outgoing deletions incoming, the local will not exist but
// it is still important to unmanage (e.g. delete all meta info) for the
// deletion.
CVSWorkspaceRoot.getCVSResourceFor(getLocal()).unmanage(monitor);
}
/*
* Load the resource and folder sync info into the local from the remote
*
* This method can be used on incoming folder additions to set the folder sync info properly
* without hitting the server again. It also applies to conflicts that involves unmanaged
* local resources.
*
* @return an IStatus with the following severity and codes
* <ul>
* <li>IStatus.WARNING
* <ul>
* <li>INVALID_RESOURCE_TYPE - makeInSync only works on folders
* <li>INVALID_SYNC_KIND - sync direction must be incoming or conflicting
* </ul>
* <li>IStatus.ERROR
* <ul>
* <li>PARENT_NOT_MANAGED - the local parent of the resource is not under CVS control
* <li>SYNC_INFO_CONFLICTS - Sync info already exists locally and differs from the info
* in the remote handle.
* <li>REMOTE_DOES_NOT_EXIST - There is no local sync info and there is no remote handle
* </ul>
* </ul>
*/
public IStatus makeInSync() throws CVSException {
// Only works on folders
if (getLocal().getType() == IResource.FILE) {
return new CVSStatus(IStatus.WARNING, INVALID_RESOURCE_TYPE, Policy.bind("CVSSyncInfo.7", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
// Only works on outgoing and conflicting changes
boolean outgoing = (getKind() & DIRECTION_MASK) == OUTGOING;
if (outgoing) {
return new CVSStatus(IStatus.WARNING, INVALID_SYNC_KIND, Policy.bind("CVSSyncInfo.8", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
// The parent must be managed
ICVSFolder local = CVSWorkspaceRoot.getCVSFolderFor((IContainer)getLocal());
if (getLocal().getType() == IResource.FOLDER && ! local.getParent().isCVSFolder())
return new CVSStatus(IStatus.ERROR, PARENT_NOT_MANAGED, Policy.bind("CVSSyncInfo.9", getLocal().getFullPath().toString())); //$NON-NLS-1$
// Ensure that the folder exists locally
if (! local.exists()) {
local.mkdir();
}
// If the folder already has CVS info, check that the remote and local match
RemoteFolder remote = (RemoteFolder)getRemote();
if((local.isManaged() || getLocal().getType() == IResource.PROJECT) && local.isCVSFolder()) {
// If there's no remote, assume everything is OK
if (remote == null) return Status.OK_STATUS;
// Verify that the root and repository are the same
FolderSyncInfo remoteInfo = remote.getFolderSyncInfo();
FolderSyncInfo localInfo = local.getFolderSyncInfo();
if ( ! localInfo.getRoot().equals(remoteInfo.getRoot())) {
return new CVSStatus(IStatus.ERROR, SYNC_INFO_CONFLICTS, Policy.bind("CVSRemoteSyncElement.rootDiffers", new Object[] {local.getName(), remoteInfo.getRoot(), localInfo.getRoot()}));//$NON-NLS-1$
} else if ( ! localInfo.getRepository().equals(remoteInfo.getRepository())) {
return new CVSStatus(IStatus.ERROR, SYNC_INFO_CONFLICTS, Policy.bind("CVSRemoteSyncElement.repositoryDiffers", new Object[] {local.getName(), remoteInfo.getRepository(), localInfo.getRepository()}));//$NON-NLS-1$
}
// The folders are in sync so just return
return Status.OK_STATUS;
}
// The remote must exist if the local is not managed
if (remote == null) {
return new CVSStatus(IStatus.ERROR, REMOTE_DOES_NOT_EXIST, Policy.bind("CVSSyncInfo.10", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
// Since the parent is managed, this will also set the resource sync info. It is
// impossible for an incoming folder addition to map to another location in the
// repo, so we assume that using the parent's folder sync as a basis is safe.
// It is also impossible for an incomming folder to be static.
FolderSyncInfo remoteInfo = remote.getFolderSyncInfo();
FolderSyncInfo localInfo = local.getParent().getFolderSyncInfo();
local.setFolderSyncInfo(new FolderSyncInfo(remoteInfo.getRepository(), remoteInfo.getRoot(), localInfo.getTag(), false));
return Status.OK_STATUS;
}
public String toString() {
IResourceVariant base = getBase();
IResourceVariant remote = getRemote();
StringBuffer result = new StringBuffer(super.toString());
result.append("Local: "); //$NON-NLS-1$
result.append(getLocal().toString());
result.append(" Base: "); //$NON-NLS-1$
if (base == null) {
result.append("none"); //$NON-NLS-1$
} else {
result.append(base.toString());
}
result.append(" Remote: "); //$NON-NLS-1$
if (remote == null) {
result.append("none"); //$NON-NLS-1$
} else {
result.append(remote.toString());
}
return result.toString();
}
/* (non-Javadoc)
* @see org.eclipse.team.core.subscribers.SyncInfo#getContentIdentifier()
*/
public String getLocalContentIdentifier() {
try {
IResource local = getLocal();
if (local != null && local.getType() == IResource.FILE) {
// it's a file, return the revision number if we can find one
ICVSFile cvsFile = CVSWorkspaceRoot.getCVSFileFor((IFile) local);
ResourceSyncInfo info = cvsFile.getSyncInfo();
if (info != null) {
return info.getRevision();
}
}
} catch (CVSException e) {
CVSProviderPlugin.log(e);
return null;
}
return null;
}
}
| true | true | public IStatus makeOutgoing(IProgressMonitor monitor) throws TeamException {
// For folders, there is no outgoing, only in-sync
if (getLocal().getType() == IResource.FOLDER) {
return makeInSync();
}
int syncKind = getKind();
boolean incoming = (syncKind & DIRECTION_MASK) == INCOMING;
boolean outgoing = (syncKind & DIRECTION_MASK) == OUTGOING;
ICVSResource local = CVSWorkspaceRoot.getCVSResourceFor(getLocal());
RemoteResource remote = (RemoteResource)getRemote();
ResourceSyncInfo origInfo = local.getSyncInfo();
MutableResourceSyncInfo info = null;
if(origInfo!=null) {
info = origInfo.cloneMutable();
}
if (outgoing) {
// The sync info is alright, it's already outgoing!
return Status.OK_STATUS;
} else if (incoming) {
// We have an incoming change, addition, or deletion that we want to ignore
if (local.exists()) {
// We could have an incoming change or deletion
if (remote == null) {
info.setAdded();
} else {
// Otherwise change the revision to the remote revision and dirty the file
info.setRevision(remote.getSyncInfo().getRevision());
info.setTimeStamp(null);
}
} else {
// We have an incoming add, turn it around as an outgoing delete
info = remote.getSyncInfo().cloneMutable();
info.setDeleted(true);
}
} else if (local.exists()) {
// We have a conflict and a local resource!
if (getRemote() != null) {
if (getBase() != null) {
// We have a conflicting change, Update the local revision
info.setRevision(remote.getSyncInfo().getRevision());
} else {
try {
// We have conflictin additions.
// We need to fetch the contents of the remote to get all the relevant information (timestamp, permissions)
// The most important thing we get is the keyword substitution mode which must be right to perform the commit
remote.getStorage(Policy.monitorFor(monitor)).getContents();
info = remote.getSyncInfo().cloneMutable();
} catch (CoreException e) {
TeamException.asTeamException(e);
}
}
} else if (getBase() != null) {
// We have a remote deletion. Make the local an addition
info.setAdded();
} else {
// There's a local, no base and no remote. We can't possible have a conflict!
Assert.isTrue(false);
}
} else {
// We have a conflict and there is no local!
if (getRemote() != null) {
// We have a local deletion that conflicts with remote changes.
info.setRevision(remote.getSyncInfo().getRevision());
info.setDeleted(true);
} else {
// We have conflicting deletions. Clear the sync info
info = null;
return Status.OK_STATUS;
}
}
if(info!=null) {
FolderSyncInfo parentInfo = local.getParent().getFolderSyncInfo();
if (parentInfo == null) {
return new CVSStatus(IStatus.ERROR, PARENT_NOT_MANAGED, Policy.bind("CVSSyncInfo.9", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
info.setTag(parentInfo.getTag());
}
((ICVSFile)local).setSyncInfo(info, ICVSFile.UNKNOWN);
return Status.OK_STATUS;
}
| public IStatus makeOutgoing(IProgressMonitor monitor) throws TeamException {
// For folders, there is no outgoing, only in-sync
if (getLocal().getType() == IResource.FOLDER) {
return makeInSync();
}
int syncKind = getKind();
boolean incoming = (syncKind & DIRECTION_MASK) == INCOMING;
boolean outgoing = (syncKind & DIRECTION_MASK) == OUTGOING;
ICVSResource local = CVSWorkspaceRoot.getCVSResourceFor(getLocal());
RemoteResource remote = (RemoteResource)getRemote();
ResourceSyncInfo origInfo = local.getSyncInfo();
MutableResourceSyncInfo info = null;
if(origInfo!=null) {
info = origInfo.cloneMutable();
}
if (outgoing) {
// The sync info is alright, it's already outgoing!
return Status.OK_STATUS;
} else if (incoming) {
// We have an incoming change, addition, or deletion that we want to ignore
if (local.exists()) {
// We could have an incoming change or deletion
if (remote == null) {
info.setAdded();
} else {
// Otherwise change the revision to the remote revision and dirty the file
info.setRevision(remote.getSyncInfo().getRevision());
info.setTimeStamp(null);
}
} else {
// We have an incoming add, turn it around as an outgoing delete
info = remote.getSyncInfo().cloneMutable();
info.setDeleted(true);
}
} else if (local.exists()) {
// We have a conflict and a local resource!
if (getRemote() != null) {
if (getBase() != null) {
// We have a conflicting change, Update the local revision
info.setRevision(remote.getSyncInfo().getRevision());
} else {
try {
// We have conflictin additions.
// We need to fetch the contents of the remote to get all the relevant information (timestamp, permissions)
// The most important thing we get is the keyword substitution mode which must be right to perform the commit
remote.getStorage(Policy.monitorFor(monitor)).getContents();
info = remote.getSyncInfo().cloneMutable();
} catch (CoreException e) {
throw TeamException.asTeamException(e);
}
}
} else if (getBase() != null) {
// We have a remote deletion. Make the local an addition
info.setAdded();
} else {
// There's a local, no base and no remote. We can't possible have a conflict!
Assert.isTrue(false);
}
} else {
// We have a conflict and there is no local!
if (getRemote() != null) {
// We have a local deletion that conflicts with remote changes.
info.setRevision(remote.getSyncInfo().getRevision());
info.setDeleted(true);
} else {
// We have conflicting deletions. Clear the sync info
info = null;
return Status.OK_STATUS;
}
}
if(info!=null) {
FolderSyncInfo parentInfo = local.getParent().getFolderSyncInfo();
if (parentInfo == null) {
return new CVSStatus(IStatus.ERROR, PARENT_NOT_MANAGED, Policy.bind("CVSSyncInfo.9", getLocal().getFullPath().toString())); //$NON-NLS-1$
}
info.setTag(parentInfo.getTag());
}
((ICVSFile)local).setSyncInfo(info, ICVSFile.UNKNOWN);
return Status.OK_STATUS;
}
|
diff --git a/src/com/hughes/android/dictionary/DictionaryActivity.java b/src/com/hughes/android/dictionary/DictionaryActivity.java
index 3b01133..5d937f8 100644
--- a/src/com/hughes/android/dictionary/DictionaryActivity.java
+++ b/src/com/hughes/android/dictionary/DictionaryActivity.java
@@ -1,1190 +1,1195 @@
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.hughes.android.dictionary;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Dictionary;
import com.hughes.android.dictionary.engine.EntrySource;
import com.hughes.android.dictionary.engine.Index;
import com.hughes.android.dictionary.engine.Index.IndexEntry;
import com.hughes.android.dictionary.engine.PairEntry;
import com.hughes.android.dictionary.engine.PairEntry.Pair;
import com.hughes.android.dictionary.engine.RowBase;
import com.hughes.android.dictionary.engine.TokenRow;
import com.hughes.android.dictionary.engine.TransliteratorManager;
import com.hughes.android.util.IntentLauncher;
import com.hughes.android.util.NonLinkClickableSpan;
public class DictionaryActivity extends ListActivity {
static final String LOG = "QuickDic";
private String initialSearchText;
DictionaryApplication application;
File dictFile = null;
RandomAccessFile dictRaf = null;
Dictionary dictionary = null;
int indexIndex = 0;
Index index = null;
List<RowBase> rowsToShow = null; // if not null, just show these rows.
// package for test.
final Handler uiHandler = new Handler();
private final Executor searchExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "searchExecutor");
}
});
private SearchOperation currentSearchOperation = null;
C.Theme theme = C.Theme.LIGHT;
Typeface typeface;
int fontSizeSp;
EditText searchText;
Button langButton;
// Never null.
private File wordList = null;
private boolean saveOnlyFirstSubentry = false;
private boolean clickOpensContextMenu = false;
// Visible for testing.
ListAdapter indexAdapter = null;
final SearchTextWatcher searchTextWatcher = new SearchTextWatcher();
/**
* For some languages, loading the transliterators used in this search takes
* a long time, so we fire it up on a different thread, and don't invoke it
* from the main thread until it's already finished once.
*/
private volatile boolean indexPrepFinished = false;
public DictionaryActivity() {
}
public static Intent getLaunchIntent(final File dictFile, final int indexIndex, final String searchToken) {
final Intent intent = new Intent();
intent.setClassName(DictionaryActivity.class.getPackage().getName(), DictionaryActivity.class.getName());
intent.putExtra(C.DICT_FILE, dictFile.getPath());
intent.putExtra(C.INDEX_INDEX, indexIndex);
intent.putExtra(C.SEARCH_TOKEN, searchToken);
return intent;
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOG, "onSaveInstanceState: " + searchText.getText().toString());
outState.putInt(C.INDEX_INDEX, indexIndex);
outState.putString(C.SEARCH_TOKEN, searchText.getText().toString());
}
@Override
protected void onRestoreInstanceState(final Bundle outState) {
super.onRestoreInstanceState(outState);
Log.d(LOG, "onRestoreInstanceState: " + outState.getString(C.SEARCH_TOKEN));
onCreate(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if this fails.
setTheme(((DictionaryApplication)getApplication()).getSelectedTheme().themeId);
Log.d(LOG, "onCreate:" + this);
super.onCreate(savedInstanceState);
application = (DictionaryApplication) getApplication();
theme = application.getSelectedTheme();
final Intent intent = getIntent();
dictFile = new File(intent.getStringExtra(C.DICT_FILE));
try {
final String name = application.getDictionaryName(dictFile.getName());
this.setTitle("QuickDic: " + name);
dictRaf = new RandomAccessFile(dictFile, "r");
dictionary = new Dictionary(dictRaf);
} catch (Exception e) {
Log.e(LOG, "Unable to load dictionary.", e);
if (dictRaf != null) {
try {
dictRaf.close();
} catch (IOException e1) {
Log.e(LOG, "Unable to close dictRaf.", e1);
}
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent());
finish();
return;
}
indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
if (savedInstanceState != null) {
indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
}
indexIndex %= dictionary.indices.size();
Log.d(LOG, "Loading index " + indexIndex);
index = dictionary.indices.get(indexIndex);
setListAdapter(new IndexAdapter(index));
// Pre-load the collators.
new Thread(new Runnable() {
public void run() {
final long startMillis = System.currentTimeMillis();
try {
TransliteratorManager.init(new TransliteratorManager.Callback() {
@Override
public void onTransliteratorReady() {
uiHandler.post(new Runnable() {
@Override
public void run() {
onSearchTextChange(searchText.getText().toString());
}
});
}
});
for (final Index index : dictionary.indices) {
final String searchToken = index.sortedIndexEntries.get(0).token;
final IndexEntry entry = index.findExact(searchToken);
if (!searchToken.equals(entry.token)) {
Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
}
}
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG, "Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:"
+ (System.currentTimeMillis() - startMillis));
}
}).start();
final String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
} else {
- typeface = Typeface.createFromAsset(getAssets(), fontName);
+ try {
+ typeface = Typeface.createFromAsset(getAssets(), fontName);
+ } catch (Exception e) {
+ Log.w(LOG, "Exception trying to use typeface, using default.", e);
+ Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()), Toast.LENGTH_LONG).show();
+ }
}
if (typeface == null) {
Log.w(LOG, "Unable to create typeface, using default.");
typeface = Typeface.DEFAULT;
}
final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
try {
fontSizeSp = Integer.parseInt(fontSize.trim());
} catch (NumberFormatException e) {
fontSizeSp = 14;
}
setContentView(R.layout.dictionary_activity);
searchText = (EditText) findViewById(R.id.SearchText);
searchText.setTypeface(typeface);
searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
langButton = (Button) findViewById(R.id.LangButton);
searchText.requestFocus();
searchText.addTextChangedListener(searchTextWatcher);
String text = "";
if (savedInstanceState != null) {
text = savedInstanceState.getString(C.SEARCH_TOKEN);
if (text == null) {
text = "";
}
}
setSearchText(text, true);
Log.d(LOG, "Trying to restore searchText=" + text);
final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
clearSearchTextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onClearSearchTextButton(clearSearchTextButton);
}
});
clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
: View.GONE);
final Button langButton = (Button) findViewById(R.id.LangButton);
langButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onLanguageButton();
}
});
langButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLanguageButtonLongClick(v.getContext());
return true;
}
});
updateLangButton();
final Button upButton = (Button) findViewById(R.id.UpButton);
upButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(true);
}
});
final Button downButton = (Button) findViewById(R.id.DownButton);
downButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(false);
}
});
getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
long id) {
if (!searchText.isFocused()) {
if (!isFiltered()) {
final RowBase row = (RowBase) getListAdapter().getItem(position);
Log.d(LOG, "onItemSelected: " + row.index());
final TokenRow tokenRow = row.getTokenRow(true);
searchText.setText(tokenRow.getToken());
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ContextMenu.
registerForContextMenu(getListView());
// Prefs.
wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
getString(R.string.wordListFileDefault)));
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
//if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
// vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//}
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
}
@Override
protected void onResume() {
super.onResume();
if (PreferenceActivity.prefsMightHaveChanged) {
PreferenceActivity.prefsMightHaveChanged = false;
finish();
startActivity(getIntent());
}
if (initialSearchText != null) {
setSearchText(initialSearchText, true);
}
}
@Override
protected void onPause() {
super.onPause();
}
private static void setDictionaryPrefs(final Context context,
final File dictFile, final int indexIndex, final String searchToken) {
final SharedPreferences.Editor prefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
prefs.putString(C.DICT_FILE, dictFile.getPath());
prefs.putInt(C.INDEX_INDEX, indexIndex);
prefs.putString(C.SEARCH_TOKEN, searchToken);
prefs.commit();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (dictRaf == null) {
return;
}
final SearchOperation searchOperation = currentSearchOperation;
currentSearchOperation = null;
// Before we close the RAF, we have to wind the current search down.
if (searchOperation != null) {
Log.d(LOG, "Interrupting search to shut down.");
currentSearchOperation = null;
searchOperation.interrupted.set(true);
}
try {
Log.d(LOG, "Closing RAF.");
dictRaf.close();
} catch (IOException e) {
Log.e(LOG, "Failed to close dictionary", e);
}
dictRaf = null;
}
// --------------------------------------------------------------------------
// Buttons
// --------------------------------------------------------------------------
private void onClearSearchTextButton(final Button clearSearchTextButton) {
setSearchText("", true);
Log.d(LOG, "Trying to show soft keyboard.");
final InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT);
}
void updateLangButton() {
// final LanguageResources languageResources = Language.isoCodeToResources.get(index.shortName);
// if (languageResources != null && languageResources.flagId != 0) {
// langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, languageResources.flagId, 0);
// } else {
// langButton.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
langButton.setText(index.shortName);
// }
}
void onLanguageButton() {
if (currentSearchOperation != null) {
currentSearchOperation.interrupted.set(true);
currentSearchOperation = null;
}
changeIndexGetFocusAndResearch((indexIndex + 1)% dictionary.indices.size());
}
void onLanguageButtonLongClick(final Context context) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.select_dictionary_dialog);
dialog.setTitle(R.string.selectDictionary);
final List<DictionaryInfo> installedDicts = ((DictionaryApplication)getApplication()).getUsableDicts();
ListView listView = (ListView) dialog.findViewById(android.R.id.list);
// final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// layoutParams.width = 0;
// layoutParams.weight = 1.0f;
final Button button = new Button(listView.getContext());
final String name = getString(R.string.dictionaryManager);
button.setText(name);
final IntentLauncher intentLauncher = new IntentLauncher(listView.getContext(), DictionaryManagerActivity.getLaunchIntent()) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
};
};
button.setOnClickListener(intentLauncher);
// button.setLayoutParams(layoutParams);
listView.addHeaderView(button);
// listView.setHeaderDividersEnabled(true);
listView.setAdapter(new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final LinearLayout result = new LinearLayout(parent.getContext());
final DictionaryInfo dictionaryInfo = getItem(position);
final Button button = new Button(parent.getContext());
final String name = application.getDictionaryName(dictionaryInfo.uncompressedFilename);
button.setText(name);
final IntentLauncher intentLauncher = new IntentLauncher(parent.getContext(), getLaunchIntent(application.getPath(dictionaryInfo.uncompressedFilename), 0, searchText.getText().toString())) {
@Override
protected void onGo() {
dialog.dismiss();
DictionaryActivity.this.finish();
};
};
button.setOnClickListener(intentLauncher);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.width = 0;
layoutParams.weight = 1.0f;
button.setLayoutParams(layoutParams);
result.addView(button);
return result;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public DictionaryInfo getItem(int position) {
return installedDicts.get(position);
}
@Override
public int getCount() {
return installedDicts.size();
}
});
dialog.show();
}
private void changeIndexGetFocusAndResearch(final int newIndex) {
indexIndex = newIndex;
index = dictionary.indices.get(indexIndex);
indexAdapter = new IndexAdapter(index);
Log.d(LOG, "changingIndex, newLang=" + index.longName);
setListAdapter(indexAdapter);
updateLangButton();
searchText.requestFocus(); // Otherwise, nothing may happen.
onSearchTextChange(searchText.getText().toString());
setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
}
void onUpDownButton(final boolean up) {
if (isFiltered()) {
return;
}
final int firstVisibleRow = getListView().getFirstVisiblePosition();
final RowBase row = index.rows.get(firstVisibleRow);
final TokenRow tokenRow = row.getTokenRow(true);
final int destIndexEntry;
if (up) {
if (row != tokenRow) {
destIndexEntry = tokenRow.referenceIndex;
} else {
destIndexEntry = Math.max(tokenRow.referenceIndex - 1, 0);
}
} else {
// Down
destIndexEntry = Math.min(tokenRow.referenceIndex + 1, index.sortedIndexEntries.size());
}
final Index.IndexEntry dest = index.sortedIndexEntries.get(destIndexEntry);
Log.d(LOG, "onUpDownButton, destIndexEntry=" + dest.token);
searchText.removeTextChangedListener(searchTextWatcher);
searchText.setText(dest.token);
if (searchText.getLayout() != null) {
// Surprising, but this can otherwise crash sometimes...
Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
}
jumpToRow(index.sortedIndexEntries.get(destIndexEntry).startRow);
searchText.addTextChangedListener(searchTextWatcher);
}
// --------------------------------------------------------------------------
// Options Menu
// --------------------------------------------------------------------------
final Random random = new Random();
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
application.onCreateGlobalOptionsMenu(this, menu);
{
final MenuItem randomWord = menu.add(getString(R.string.randomWord));
randomWord.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
final String word = index.sortedIndexEntries.get(random.nextInt(index.sortedIndexEntries.size())).token;
setSearchText(word, true);
return false;
}
});
}
{
final MenuItem dictionaryList = menu.add(getString(R.string.dictionaryManager));
dictionaryList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
startActivity(DictionaryManagerActivity.getLaunchIntent());
finish();
return false;
}
});
}
{
final MenuItem aboutDictionary = menu.add(getString(R.string.aboutDictionary));
aboutDictionary.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(final MenuItem menuItem) {
final Context context = getListView().getContext();
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.about_dictionary_dialog);
final TextView textView = (TextView) dialog.findViewById(R.id.text);
final String name = application.getDictionaryName(dictFile.getName());
dialog.setTitle(name);
final StringBuilder builder = new StringBuilder();
final DictionaryInfo dictionaryInfo = dictionary.getDictionaryInfo();
dictionaryInfo.uncompressedBytes = dictFile.length();
if (dictionaryInfo != null) {
builder.append(dictionaryInfo.dictInfo).append("\n\n");
builder.append(getString(R.string.dictionaryPath, dictFile.getPath())).append("\n");
builder.append(getString(R.string.dictionarySize, dictionaryInfo.uncompressedBytes)).append("\n");
builder.append(getString(R.string.dictionaryCreationTime, dictionaryInfo.creationMillis)).append("\n");
for (final IndexInfo indexInfo : dictionaryInfo.indexInfos) {
builder.append("\n");
builder.append(getString(R.string.indexName, indexInfo.shortName)).append("\n");
builder.append(getString(R.string.mainTokenCount, indexInfo.mainTokenCount)).append("\n");
}
builder.append("\n");
builder.append(getString(R.string.sources)).append("\n");
for (final EntrySource source : dictionary.sources) {
builder.append(getString(R.string.sourceInfo, source.getName(), source.getNumEntries())).append("\n");
}
}
// } else {
// builder.append(getString(R.string.invalidDictionary));
// }
textView.setText(builder.toString());
dialog.show();
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.FILL_PARENT;
layoutParams.height = WindowManager.LayoutParams.FILL_PARENT;
dialog.getWindow().setAttributes(layoutParams);
return false;
}
});
}
return true;
}
// --------------------------------------------------------------------------
// Context Menu + clicks
// --------------------------------------------------------------------------
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) menuInfo;
final RowBase row = (RowBase) getListAdapter().getItem(adapterContextMenuInfo.position);
final MenuItem addToWordlist = menu.add(getString(R.string.addToWordList, wordList.getName()));
addToWordlist.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
onAppendToWordList(row);
return false;
}
});
final MenuItem copy = menu.add(android.R.string.copy);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
onCopy(row);
return false;
}
});
if (selectedSpannableText != null) {
final String selectedText = selectedSpannableText;
final MenuItem searchForSelection = menu.add(getString(R.string.searchForSelection, selectedSpannableText));
searchForSelection.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
int indexToUse = -1;
for (int i = 0; i < dictionary.indices.size(); ++i) {
final Index index = dictionary.indices.get(i);
if (indexPrepFinished) {
System.out.println("Doing index lookup: on " + selectedText);
final IndexEntry indexEntry = index.findExact(selectedText);
if (indexEntry != null) {
final TokenRow tokenRow = index.rows.get(indexEntry.startRow).getTokenRow(false);
if (tokenRow != null && tokenRow.hasMainEntry) {
indexToUse = i;
break;
}
}
} else {
Log.w(LOG, "Skipping findExact on index " + index.shortName);
}
}
if (indexToUse == -1) {
indexToUse = selectedSpannableIndex;
}
final boolean changeIndex = indexIndex != indexToUse;
setSearchText(selectedText, !changeIndex); // If we're not changing index, we have to triggerSearch.
if (changeIndex) {
changeIndexGetFocusAndResearch(indexToUse);
}
// Give focus back to list view because typing is done.
getListView().requestFocus();
return false;
}
});
}
}
@Override
protected void onListItemClick(ListView l, View v, int row, long id) {
defocusSearchText();
if (clickOpensContextMenu && dictRaf != null) {
openContextMenu(v);
}
}
void onAppendToWordList(final RowBase row) {
defocusSearchText();
final StringBuilder rawText = new StringBuilder();
rawText.append(
new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date()))
.append("\t");
rawText.append(index.longName).append("\t");
rawText.append(row.getTokenRow(true).getToken()).append("\t");
rawText.append(row.getRawText(saveOnlyFirstSubentry));
Log.d(LOG, "Writing : " + rawText);
try {
wordList.getParentFile().mkdirs();
final PrintWriter out = new PrintWriter(
new FileWriter(wordList, true));
out.println(rawText.toString());
out.close();
} catch (IOException e) {
Log.e(LOG, "Unable to append to " + wordList.getAbsolutePath(), e);
Toast.makeText(this, getString(R.string.failedAddingToWordList, wordList.getAbsolutePath()), Toast.LENGTH_LONG);
}
return;
}
/**
* Called when user clicks outside of search text, so that they can start
* typing again immediately.
*/
void defocusSearchText() {
//Log.d(LOG, "defocusSearchText");
// Request focus so that if we start typing again, it clears the text input.
getListView().requestFocus();
// Visual indication that a new keystroke will clear the search text.
searchText.selectAll();
}
void onCopy(final RowBase row) {
defocusSearchText();
Log.d(LOG, "Copy, row=" + row);
final StringBuilder result = new StringBuilder();
result.append(row.getRawText(false));
final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(result.toString());
Log.d(LOG, "Copied: " + result);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if (event.getUnicodeChar() != 0) {
if (!searchText.hasFocus()) {
setSearchText("" + (char) event.getUnicodeChar(), true);
}
return true;
}
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Log.d(LOG, "Clearing dictionary prefs.");
// Pretend that we just autolaunched so that we won't do it again.
//DictionaryManagerActivity.lastAutoLaunchMillis = System.currentTimeMillis();
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d(LOG, "Trying to hide soft keyboard.");
final InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return true;
}
return super.onKeyDown(keyCode, event);
}
private void setSearchText(final String text, final boolean triggerSearch) {
if (!triggerSearch) {
getListView().requestFocus();
}
searchText.setText(text);
searchText.requestFocus();
if (searchText.getLayout() != null) {
// Surprising, but this can crash when you rotate...
Selection.moveToRightEdge(searchText.getText(), searchText.getLayout());
}
if (triggerSearch) {
onSearchTextChange(text);
}
}
// --------------------------------------------------------------------------
// SearchOperation
// --------------------------------------------------------------------------
private void searchFinished(final SearchOperation searchOperation) {
if (searchOperation.interrupted.get()) {
Log.d(LOG, "Search operation was interrupted: " + searchOperation);
return;
}
if (searchOperation != this.currentSearchOperation) {
Log.d(LOG, "Stale searchOperation finished: " + searchOperation);
return;
}
final Index.IndexEntry searchResult = searchOperation.searchResult;
Log.d(LOG, "searchFinished: " + searchOperation + ", searchResult=" + searchResult);
currentSearchOperation = null;
uiHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (currentSearchOperation == null) {
if (searchResult != null) {
if (isFiltered()) {
clearFiltered();
}
jumpToRow(searchResult.startRow);
} else if (searchOperation.multiWordSearchResult != null) {
// Multi-row search....
setFiltered(searchOperation);
} else {
throw new IllegalStateException("This should never happen.");
}
} else {
Log.d(LOG, "More coming, waiting for currentSearchOperation.");
}
}
}, 20);
}
private final void jumpToRow(final int row) {
setSelection(row);
getListView().setSelected(true);
}
static final Pattern WHITESPACE = Pattern.compile("\\s+");
final class SearchOperation implements Runnable {
final AtomicBoolean interrupted = new AtomicBoolean(false);
final String searchText;
List<String> searchTokens; // filled in for multiWord.
final Index index;
long searchStartMillis;
Index.IndexEntry searchResult;
List<RowBase> multiWordSearchResult;
boolean done = false;
SearchOperation(final String searchText, final Index index) {
this.searchText = searchText.trim();
this.index = index;
}
public String toString() {
return String.format("SearchOperation(%s,%s)", searchText, interrupted.toString());
}
@Override
public void run() {
try {
searchStartMillis = System.currentTimeMillis();
final String[] searchTokenArray = WHITESPACE.split(searchText);
if (searchTokenArray.length == 1) {
searchResult = index.findInsertionPoint(searchText, interrupted);
} else {
searchTokens = Arrays.asList(searchTokenArray);
multiWordSearchResult = index.multiWordSearch(searchTokens, interrupted);
}
Log.d(LOG, "searchText=" + searchText + ", searchDuration="
+ (System.currentTimeMillis() - searchStartMillis) + ", interrupted="
+ interrupted.get());
if (!interrupted.get()) {
uiHandler.post(new Runnable() {
@Override
public void run() {
searchFinished(SearchOperation.this);
}
});
}
} catch (Exception e) {
Log.e(LOG, "Failure during search (can happen during Activity close.");
} finally {
synchronized (this) {
done = true;
this.notifyAll();
}
}
}
}
// --------------------------------------------------------------------------
// IndexAdapter
// --------------------------------------------------------------------------
final class IndexAdapter extends BaseAdapter {
final Index index;
final List<RowBase> rows;
final Set<String> toHighlight;
IndexAdapter(final Index index) {
this.index = index;
rows = index.rows;
this.toHighlight = null;
}
IndexAdapter(final Index index, final List<RowBase> rows, final List<String> toHighlight) {
this.index = index;
this.rows = rows;
this.toHighlight = new LinkedHashSet<String>(toHighlight);
}
@Override
public int getCount() {
return rows.size();
}
@Override
public RowBase getItem(int position) {
return rows.get(position);
}
@Override
public long getItemId(int position) {
return getItem(position).index();
}
@Override
public TableLayout getView(int position, View convertView, ViewGroup parent) {
final TableLayout result;
if (convertView instanceof TableLayout) {
result = (TableLayout) convertView;
result.removeAllViews();
} else {
result = new TableLayout(parent.getContext());
}
final RowBase row = getItem(position);
if (row instanceof PairEntry.Row) {
return getView(position, (PairEntry.Row) row, parent, result);
} else if (row instanceof TokenRow) {
return getView((TokenRow) row, parent, result);
} else {
throw new IllegalArgumentException("Unsupported Row type: " + row.getClass());
}
}
private TableLayout getView(final int position, PairEntry.Row row, ViewGroup parent, final TableLayout result) {
final PairEntry entry = row.getEntry();
final int rowCount = entry.pairs.size();
final TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
layoutParams.weight = 0.5f;
for (int r = 0; r < rowCount; ++r) {
final TableRow tableRow = new TableRow(result.getContext());
final TextView col1 = new TextView(tableRow.getContext());
final TextView col2 = new TextView(tableRow.getContext());
// Set the columns in the table.
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" • ");
tableRow.addView(bullet);
}
tableRow.addView(col1, layoutParams);
final TextView margin = new TextView(tableRow.getContext());
margin.setText(" ");
tableRow.addView(margin);
if (r > 0) {
final TextView bullet = new TextView(tableRow.getContext());
bullet.setText(" • ");
tableRow.addView(bullet);
}
tableRow.addView(col2, layoutParams);
col1.setWidth(1);
col2.setWidth(1);
// Set what's in the columns.
final Pair pair = entry.pairs.get(r);
final String col1Text = index.swapPairEntries ? pair.lang2 : pair.lang1;
final String col2Text = index.swapPairEntries ? pair.lang1 : pair.lang2;
col1.setText(col1Text, TextView.BufferType.SPANNABLE);
col2.setText(col2Text, TextView.BufferType.SPANNABLE);
// Bold the token instances in col1.
final Set<String> toBold = toHighlight != null ? this.toHighlight : Collections.singleton(row.getTokenRow(true).getToken());
final Spannable col1Spannable = (Spannable) col1.getText();
for (final String token : toBold) {
int startPos = 0;
while ((startPos = col1Text.indexOf(token, startPos)) != -1) {
col1Spannable.setSpan(new StyleSpan(Typeface.BOLD), startPos,
startPos + token.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
startPos += token.length();
}
}
createTokenLinkSpans(col1, col1Spannable, col1Text);
createTokenLinkSpans(col2, (Spannable) col2.getText(), col2Text);
col1.setTypeface(typeface);
col2.setTypeface(typeface);
col1.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
col2.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
// col2.setBackgroundResource(theme.otherLangBg);
if (index.swapPairEntries) {
col2.setOnLongClickListener(textViewLongClickListenerIndex0);
col1.setOnLongClickListener(textViewLongClickListenerIndex1);
} else {
col1.setOnLongClickListener(textViewLongClickListenerIndex0);
col2.setOnLongClickListener(textViewLongClickListenerIndex1);
}
result.addView(tableRow);
}
// Because we have a Button inside a ListView row:
// http://groups.google.com/group/android-developers/browse_thread/thread/3d96af1530a7d62a?pli=1
result.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
result.setClickable(true);
result.setFocusable(true);
result.setLongClickable(true);
result.setBackgroundResource(android.R.drawable.menuitem_background);
result.setOnClickListener(new TextView.OnClickListener() {
@Override
public void onClick(View v) {
DictionaryActivity.this.onListItemClick(getListView(), v, position, position);
}
});
return result;
}
private TableLayout getView(TokenRow row, ViewGroup parent, final TableLayout result) {
final Context context = parent.getContext();
final TextView textView = new TextView(context);
textView.setText(row.getToken());
// Doesn't work:
//textView.setTextColor(android.R.color.secondary_text_light);
textView.setTextAppearance(context, theme.tokenRowFg);
textView.setTypeface(typeface);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 5 * fontSizeSp / 4);
final TableRow tableRow = new TableRow(result.getContext());
tableRow.addView(textView);
tableRow.setBackgroundResource(row.hasMainEntry ? theme.tokenRowMainBg : theme.tokenRowOtherBg);
result.addView(tableRow);
return result;
}
}
static final Pattern CHAR_DASH = Pattern.compile("['\\p{L}\\p{M}\\p{N}]+");
private void createTokenLinkSpans(final TextView textView, final Spannable spannable, final String text) {
// Saw from the source code that LinkMovementMethod sets the selection!
// http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.1_r1/android/text/method/LinkMovementMethod.java#LinkMovementMethod
textView.setMovementMethod(LinkMovementMethod.getInstance());
final Matcher matcher = CHAR_DASH.matcher(text);
while (matcher.find()) {
spannable.setSpan(new NonLinkClickableSpan(), matcher.start(), matcher.end(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
String selectedSpannableText = null;
int selectedSpannableIndex = -1;
@Override
public boolean onTouchEvent(MotionEvent event) {
selectedSpannableText = null;
selectedSpannableIndex = -1;
return super.onTouchEvent(event);
}
private class TextViewLongClickListener implements OnLongClickListener {
final int index;
private TextViewLongClickListener(final int index) {
this.index = index;
}
@Override
public boolean onLongClick(final View v) {
final TextView textView = (TextView) v;
final int start = textView.getSelectionStart();
final int end = textView.getSelectionEnd();
if (start >= 0 && end >= 0) {
selectedSpannableText = textView.getText().subSequence(start, end).toString();
selectedSpannableIndex = index;
}
return false;
}
}
final TextViewLongClickListener textViewLongClickListenerIndex0 = new TextViewLongClickListener(0);
final TextViewLongClickListener textViewLongClickListenerIndex1 = new TextViewLongClickListener(1);
// --------------------------------------------------------------------------
// SearchText
// --------------------------------------------------------------------------
void onSearchTextChange(final String text) {
if ("thadolina".equals(text)) {
final Dialog dialog = new Dialog(getListView().getContext());
dialog.setContentView(R.layout.thadolina_dialog);
dialog.setTitle("Ti amo, amore mio!");
final ImageView imageView = (ImageView) dialog.findViewById(R.id.thadolina_image);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://sites.google.com/site/cfoxroxvday/vday2012"));
startActivity(intent);
}
});
dialog.show();
}
if (dictRaf == null) {
Log.d(LOG, "searchText changed during shutdown, doing nothing.");
return;
}
if (!searchText.isFocused()) {
Log.d(LOG, "searchText changed without focus, doing nothing.");
return;
}
Log.d(LOG, "onSearchTextChange: " + text);
if (currentSearchOperation != null) {
Log.d(LOG, "Interrupting currentSearchOperation.");
currentSearchOperation.interrupted.set(true);
}
currentSearchOperation = new SearchOperation(text, index);
searchExecutor.execute(currentSearchOperation);
}
private class SearchTextWatcher implements TextWatcher {
public void afterTextChanged(final Editable searchTextEditable) {
if (searchText.hasFocus()) {
Log.d(LOG, "Search text changed with focus: " + searchText.getText());
// If they were typing to cause the change, update the UI.
onSearchTextChange(searchText.getText().toString());
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
}
// --------------------------------------------------------------------------
// Filtered results.
// --------------------------------------------------------------------------
boolean isFiltered() {
return rowsToShow != null;
}
void setFiltered(final SearchOperation searchOperation) {
((Button) findViewById(R.id.UpButton)).setEnabled(false);
((Button) findViewById(R.id.DownButton)).setEnabled(false);
rowsToShow = searchOperation.multiWordSearchResult;
setListAdapter(new IndexAdapter(index, rowsToShow, searchOperation.searchTokens));
}
void clearFiltered() {
((Button) findViewById(R.id.UpButton)).setEnabled(true);
((Button) findViewById(R.id.DownButton)).setEnabled(true);
setListAdapter(new IndexAdapter(index));
rowsToShow = null;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if this fails.
setTheme(((DictionaryApplication)getApplication()).getSelectedTheme().themeId);
Log.d(LOG, "onCreate:" + this);
super.onCreate(savedInstanceState);
application = (DictionaryApplication) getApplication();
theme = application.getSelectedTheme();
final Intent intent = getIntent();
dictFile = new File(intent.getStringExtra(C.DICT_FILE));
try {
final String name = application.getDictionaryName(dictFile.getName());
this.setTitle("QuickDic: " + name);
dictRaf = new RandomAccessFile(dictFile, "r");
dictionary = new Dictionary(dictRaf);
} catch (Exception e) {
Log.e(LOG, "Unable to load dictionary.", e);
if (dictRaf != null) {
try {
dictRaf.close();
} catch (IOException e1) {
Log.e(LOG, "Unable to close dictRaf.", e1);
}
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent());
finish();
return;
}
indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
if (savedInstanceState != null) {
indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
}
indexIndex %= dictionary.indices.size();
Log.d(LOG, "Loading index " + indexIndex);
index = dictionary.indices.get(indexIndex);
setListAdapter(new IndexAdapter(index));
// Pre-load the collators.
new Thread(new Runnable() {
public void run() {
final long startMillis = System.currentTimeMillis();
try {
TransliteratorManager.init(new TransliteratorManager.Callback() {
@Override
public void onTransliteratorReady() {
uiHandler.post(new Runnable() {
@Override
public void run() {
onSearchTextChange(searchText.getText().toString());
}
});
}
});
for (final Index index : dictionary.indices) {
final String searchToken = index.sortedIndexEntries.get(0).token;
final IndexEntry entry = index.findExact(searchToken);
if (!searchToken.equals(entry.token)) {
Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
}
}
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG, "Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:"
+ (System.currentTimeMillis() - startMillis));
}
}).start();
final String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
} else {
typeface = Typeface.createFromAsset(getAssets(), fontName);
}
if (typeface == null) {
Log.w(LOG, "Unable to create typeface, using default.");
typeface = Typeface.DEFAULT;
}
final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
try {
fontSizeSp = Integer.parseInt(fontSize.trim());
} catch (NumberFormatException e) {
fontSizeSp = 14;
}
setContentView(R.layout.dictionary_activity);
searchText = (EditText) findViewById(R.id.SearchText);
searchText.setTypeface(typeface);
searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
langButton = (Button) findViewById(R.id.LangButton);
searchText.requestFocus();
searchText.addTextChangedListener(searchTextWatcher);
String text = "";
if (savedInstanceState != null) {
text = savedInstanceState.getString(C.SEARCH_TOKEN);
if (text == null) {
text = "";
}
}
setSearchText(text, true);
Log.d(LOG, "Trying to restore searchText=" + text);
final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
clearSearchTextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onClearSearchTextButton(clearSearchTextButton);
}
});
clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
: View.GONE);
final Button langButton = (Button) findViewById(R.id.LangButton);
langButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onLanguageButton();
}
});
langButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLanguageButtonLongClick(v.getContext());
return true;
}
});
updateLangButton();
final Button upButton = (Button) findViewById(R.id.UpButton);
upButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(true);
}
});
final Button downButton = (Button) findViewById(R.id.DownButton);
downButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(false);
}
});
getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
long id) {
if (!searchText.isFocused()) {
if (!isFiltered()) {
final RowBase row = (RowBase) getListAdapter().getItem(position);
Log.d(LOG, "onItemSelected: " + row.index());
final TokenRow tokenRow = row.getTokenRow(true);
searchText.setText(tokenRow.getToken());
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ContextMenu.
registerForContextMenu(getListView());
// Prefs.
wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
getString(R.string.wordListFileDefault)));
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
//if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
// vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//}
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
}
| public void onCreate(Bundle savedInstanceState) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().remove(C.INDEX_INDEX).commit(); // Don't auto-launch if this fails.
setTheme(((DictionaryApplication)getApplication()).getSelectedTheme().themeId);
Log.d(LOG, "onCreate:" + this);
super.onCreate(savedInstanceState);
application = (DictionaryApplication) getApplication();
theme = application.getSelectedTheme();
final Intent intent = getIntent();
dictFile = new File(intent.getStringExtra(C.DICT_FILE));
try {
final String name = application.getDictionaryName(dictFile.getName());
this.setTitle("QuickDic: " + name);
dictRaf = new RandomAccessFile(dictFile, "r");
dictionary = new Dictionary(dictRaf);
} catch (Exception e) {
Log.e(LOG, "Unable to load dictionary.", e);
if (dictRaf != null) {
try {
dictRaf.close();
} catch (IOException e1) {
Log.e(LOG, "Unable to close dictRaf.", e1);
}
dictRaf = null;
}
Toast.makeText(this, getString(R.string.invalidDictionary, "", e.getMessage()), Toast.LENGTH_LONG).show();
startActivity(DictionaryManagerActivity.getLaunchIntent());
finish();
return;
}
indexIndex = intent.getIntExtra(C.INDEX_INDEX, 0);
if (savedInstanceState != null) {
indexIndex = savedInstanceState.getInt(C.INDEX_INDEX, indexIndex);
}
indexIndex %= dictionary.indices.size();
Log.d(LOG, "Loading index " + indexIndex);
index = dictionary.indices.get(indexIndex);
setListAdapter(new IndexAdapter(index));
// Pre-load the collators.
new Thread(new Runnable() {
public void run() {
final long startMillis = System.currentTimeMillis();
try {
TransliteratorManager.init(new TransliteratorManager.Callback() {
@Override
public void onTransliteratorReady() {
uiHandler.post(new Runnable() {
@Override
public void run() {
onSearchTextChange(searchText.getText().toString());
}
});
}
});
for (final Index index : dictionary.indices) {
final String searchToken = index.sortedIndexEntries.get(0).token;
final IndexEntry entry = index.findExact(searchToken);
if (!searchToken.equals(entry.token)) {
Log.e(LOG, "Couldn't find token: " + searchToken + ", " + entry.token);
}
}
indexPrepFinished = true;
} catch (Exception e) {
Log.w(LOG, "Exception while prepping. This can happen if dictionary is closed while search is happening.");
}
Log.d(LOG, "Prepping indices took:"
+ (System.currentTimeMillis() - startMillis));
}
}).start();
final String fontName = prefs.getString(getString(R.string.fontKey), "FreeSerif.ttf.jpg");
if ("SYSTEM".equals(fontName)) {
typeface = Typeface.DEFAULT;
} else {
try {
typeface = Typeface.createFromAsset(getAssets(), fontName);
} catch (Exception e) {
Log.w(LOG, "Exception trying to use typeface, using default.", e);
Toast.makeText(this, getString(R.string.fontFailure, e.getLocalizedMessage()), Toast.LENGTH_LONG).show();
}
}
if (typeface == null) {
Log.w(LOG, "Unable to create typeface, using default.");
typeface = Typeface.DEFAULT;
}
final String fontSize = prefs.getString(getString(R.string.fontSizeKey), "14");
try {
fontSizeSp = Integer.parseInt(fontSize.trim());
} catch (NumberFormatException e) {
fontSizeSp = 14;
}
setContentView(R.layout.dictionary_activity);
searchText = (EditText) findViewById(R.id.SearchText);
searchText.setTypeface(typeface);
searchText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSizeSp);
langButton = (Button) findViewById(R.id.LangButton);
searchText.requestFocus();
searchText.addTextChangedListener(searchTextWatcher);
String text = "";
if (savedInstanceState != null) {
text = savedInstanceState.getString(C.SEARCH_TOKEN);
if (text == null) {
text = "";
}
}
setSearchText(text, true);
Log.d(LOG, "Trying to restore searchText=" + text);
final Button clearSearchTextButton = (Button) findViewById(R.id.ClearSearchTextButton);
clearSearchTextButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onClearSearchTextButton(clearSearchTextButton);
}
});
clearSearchTextButton.setVisibility(PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
getString(R.string.showClearSearchTextButtonKey), true) ? View.VISIBLE
: View.GONE);
final Button langButton = (Button) findViewById(R.id.LangButton);
langButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onLanguageButton();
}
});
langButton.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onLanguageButtonLongClick(v.getContext());
return true;
}
});
updateLangButton();
final Button upButton = (Button) findViewById(R.id.UpButton);
upButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(true);
}
});
final Button downButton = (Button) findViewById(R.id.DownButton);
downButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
onUpDownButton(false);
}
});
getListView().setOnItemSelectedListener(new ListView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View arg1, final int position,
long id) {
if (!searchText.isFocused()) {
if (!isFiltered()) {
final RowBase row = (RowBase) getListAdapter().getItem(position);
Log.d(LOG, "onItemSelected: " + row.index());
final TokenRow tokenRow = row.getTokenRow(true);
searchText.setText(tokenRow.getToken());
}
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ContextMenu.
registerForContextMenu(getListView());
// Prefs.
wordList = new File(prefs.getString(getString(R.string.wordListFileKey),
getString(R.string.wordListFileDefault)));
saveOnlyFirstSubentry = prefs.getBoolean(getString(R.string.saveOnlyFirstSubentryKey), false);
clickOpensContextMenu = prefs.getBoolean(getString(R.string.clickOpensContextMenuKey), false);
//if (prefs.getBoolean(getString(R.string.vibrateOnFailedSearchKey), true)) {
// vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//}
Log.d(LOG, "wordList=" + wordList + ", saveOnlyFirstSubentry=" + saveOnlyFirstSubentry);
setDictionaryPrefs(this, dictFile, indexIndex, searchText.getText().toString());
}
|
diff --git a/nuxeo-social-workspace/nuxeo-social-workspace-core/src/main/java/org/nuxeo/ecm/social/workspace/listeners/SocialWorkspaceMembersManagementListener.java b/nuxeo-social-workspace/nuxeo-social-workspace-core/src/main/java/org/nuxeo/ecm/social/workspace/listeners/SocialWorkspaceMembersManagementListener.java
index ffc4f039..e41019b4 100644
--- a/nuxeo-social-workspace/nuxeo-social-workspace-core/src/main/java/org/nuxeo/ecm/social/workspace/listeners/SocialWorkspaceMembersManagementListener.java
+++ b/nuxeo-social-workspace/nuxeo-social-workspace-core/src/main/java/org/nuxeo/ecm/social/workspace/listeners/SocialWorkspaceMembersManagementListener.java
@@ -1,225 +1,225 @@
/*
* (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo
*/
package org.nuxeo.ecm.social.workspace.listeners;
import static org.nuxeo.ecm.social.workspace.SocialConstants.CTX_PRINCIPALS_PROPERTY;
import static org.nuxeo.ecm.social.workspace.SocialConstants.EVENT_MEMBERS_ADDED;
import static org.nuxeo.ecm.social.workspace.SocialConstants.EVENT_MEMBERS_REMOVED;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.utils.FileUtils;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationChain;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.operations.notification.SendMail;
import org.nuxeo.ecm.automation.core.scripting.Expression;
import org.nuxeo.ecm.automation.core.scripting.Scripting;
import org.nuxeo.ecm.automation.core.util.StringList;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.ClientRuntimeException;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventBundle;
import org.nuxeo.ecm.core.event.PostCommitEventListener;
import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
import org.nuxeo.ecm.platform.ui.web.tag.fn.Functions;
import org.nuxeo.ecm.platform.usermanager.UserManager;
import org.nuxeo.ecm.social.workspace.adapters.SocialWorkspace;
import org.nuxeo.ecm.social.workspace.service.SocialWorkspaceServiceImpl;
import org.nuxeo.runtime.api.Framework;
/**
* Listener to notify members about added or removed social workspace members
*
* @author Arnaud Kervern <[email protected]>
* @since 5.5
*/
public class SocialWorkspaceMembersManagementListener implements
PostCommitEventListener {
private static Log log = LogFactory.getLog(SocialWorkspaceMembersManagementListener.class);
private static final String TEMPLATE_ADDED = "templates/memberNotification.ftl";
@Override
public void handleEvent(EventBundle eventBundle) throws ClientException {
Map<DocumentRef, List<Event>> socialDocuments = new HashMap<DocumentRef, List<Event>>();
if (!(eventBundle.containsEventName(EVENT_MEMBERS_ADDED) || eventBundle.containsEventName(EVENT_MEMBERS_REMOVED))) {
return;
}
for (Event event : eventBundle) {
String eventName = event.getName();
if (EVENT_MEMBERS_ADDED.equals(eventName)
|| EVENT_MEMBERS_REMOVED.equals(eventName)) {
addDocumentContextToMap(socialDocuments, event);
}
}
for (Map.Entry<DocumentRef, List<Event>> entry : socialDocuments.entrySet()) {
notifyForDocument(entry);
}
}
public void addDocumentContextToMap(
Map<DocumentRef, List<Event>> socialDocuments, Event event) {
DocumentEventContext docCtx = (DocumentEventContext) event.getContext();
DocumentRef docRef = docCtx.getSourceDocument().getRef();
if (socialDocuments.containsKey(docRef)) {
socialDocuments.get(docRef).add(event);
} else {
List<Event> docContextes = new ArrayList<Event>();
docContextes.add(event);
socialDocuments.put(docRef, docContextes);
}
}
private void notifyForDocument(
Map.Entry<DocumentRef, List<Event>> eventContexts) {
List<Principal> addedMembers = new ArrayList<Principal>();
List<Principal> removedMembers = new ArrayList<Principal>();
for (Event event : eventContexts.getValue()) {
DocumentEventContext docCtx = (DocumentEventContext) event.getContext();
List<Principal> principals = (List<Principal>) docCtx.getProperty(CTX_PRINCIPALS_PROPERTY);
if (event.getName().equals(EVENT_MEMBERS_ADDED)) {
addedMembers.addAll(principals);
} else if (event.getName().equals(EVENT_MEMBERS_REMOVED)) {
removedMembers.addAll(principals);
}
}
if (!addedMembers.isEmpty() || !removedMembers.isEmpty()) {
DocumentEventContext context = (DocumentEventContext) eventContexts.getValue().get(
0).getContext();
notifyMembers(context, addedMembers, removedMembers);
}
}
public void notifyMembers(DocumentEventContext docCtx,
List<Principal> addedMembers, List<Principal> removedMembers) {
SocialWorkspace sw = docCtx.getSourceDocument().getAdapter(
SocialWorkspace.class);
if (sw == null) {
log.info("Event is handling a non social workspace document");
return;
}
OperationContext ctx = new OperationContext(docCtx.getCoreSession());
ctx.setInput(docCtx.getSourceDocument());
ctx.put("addedMembers", buildPrincipalsString(addedMembers));
ctx.put("removedMembers", buildPrincipalsString(removedMembers));
Expression from = Scripting.newExpression("Env[\"mail.from\"]");
// join both list to remove email of directly affected members
addedMembers.addAll(removedMembers);
StringList to = buildRecipientsList(sw, addedMembers);
if (to.isEmpty()) {
log.info("No recipients found for member notification in"
+ docCtx.getSourceDocument().getId());
return;
}
String subject = "Member Activity of " + sw.getTitle();
String template = TEMPLATE_ADDED;
String message = loadTemplate(template);
try {
OperationChain chain = new OperationChain("SendMail");
chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML",
true).set("subject", subject).set("message", message);
Framework.getLocalService(AutomationService.class).run(ctx, chain);
} catch (Exception e) {
- log.error("Unable to notify about a member management.", e);
+ log.warn("Unable to notify members about a member management.", e);
log.debug(e, e);
}
}
private List<String> buildPrincipalsString(List<Principal> principals) {
List<String> ret = new ArrayList<String>();
for (Principal principal : principals) {
ret.add(Functions.principalFullName((NuxeoPrincipal) principal));
}
Collections.sort(ret);
return ret;
}
private StringList buildRecipientsList(SocialWorkspace socialWorkspace,
List<Principal> principals) {
Set<String> emails = new HashSet<String>();
List<String> members = socialWorkspace.getMembers();
// Cleanup members list, to remove affected user
for (Principal principal : principals) {
members.remove(principal.getName());
}
UserManager userManager = Framework.getLocalService(UserManager.class);
for (String username : members) {
try {
String email = userManager.getPrincipal(username).getEmail();
if (!StringUtils.isBlank(email)) {
emails.add(email);
}
} catch (ClientException e) {
log.info(String.format("Trying to fetch an unknown user: %s",
username));
log.debug(e, e);
}
}
return new StringList(emails);
}
private static String loadTemplate(String key) {
InputStream io = SocialWorkspaceServiceImpl.class.getClassLoader().getResourceAsStream(
key);
if (io != null) {
try {
return FileUtils.read(io);
} catch (IOException e) {
throw new ClientRuntimeException(e);
} finally {
try {
io.close();
} catch (IOException e) {
// nothing to do
}
}
}
return null;
}
}
| true | true | public void notifyMembers(DocumentEventContext docCtx,
List<Principal> addedMembers, List<Principal> removedMembers) {
SocialWorkspace sw = docCtx.getSourceDocument().getAdapter(
SocialWorkspace.class);
if (sw == null) {
log.info("Event is handling a non social workspace document");
return;
}
OperationContext ctx = new OperationContext(docCtx.getCoreSession());
ctx.setInput(docCtx.getSourceDocument());
ctx.put("addedMembers", buildPrincipalsString(addedMembers));
ctx.put("removedMembers", buildPrincipalsString(removedMembers));
Expression from = Scripting.newExpression("Env[\"mail.from\"]");
// join both list to remove email of directly affected members
addedMembers.addAll(removedMembers);
StringList to = buildRecipientsList(sw, addedMembers);
if (to.isEmpty()) {
log.info("No recipients found for member notification in"
+ docCtx.getSourceDocument().getId());
return;
}
String subject = "Member Activity of " + sw.getTitle();
String template = TEMPLATE_ADDED;
String message = loadTemplate(template);
try {
OperationChain chain = new OperationChain("SendMail");
chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML",
true).set("subject", subject).set("message", message);
Framework.getLocalService(AutomationService.class).run(ctx, chain);
} catch (Exception e) {
log.error("Unable to notify about a member management.", e);
log.debug(e, e);
}
}
| public void notifyMembers(DocumentEventContext docCtx,
List<Principal> addedMembers, List<Principal> removedMembers) {
SocialWorkspace sw = docCtx.getSourceDocument().getAdapter(
SocialWorkspace.class);
if (sw == null) {
log.info("Event is handling a non social workspace document");
return;
}
OperationContext ctx = new OperationContext(docCtx.getCoreSession());
ctx.setInput(docCtx.getSourceDocument());
ctx.put("addedMembers", buildPrincipalsString(addedMembers));
ctx.put("removedMembers", buildPrincipalsString(removedMembers));
Expression from = Scripting.newExpression("Env[\"mail.from\"]");
// join both list to remove email of directly affected members
addedMembers.addAll(removedMembers);
StringList to = buildRecipientsList(sw, addedMembers);
if (to.isEmpty()) {
log.info("No recipients found for member notification in"
+ docCtx.getSourceDocument().getId());
return;
}
String subject = "Member Activity of " + sw.getTitle();
String template = TEMPLATE_ADDED;
String message = loadTemplate(template);
try {
OperationChain chain = new OperationChain("SendMail");
chain.add(SendMail.ID).set("from", from).set("to", to).set("HTML",
true).set("subject", subject).set("message", message);
Framework.getLocalService(AutomationService.class).run(ctx, chain);
} catch (Exception e) {
log.warn("Unable to notify members about a member management.", e);
log.debug(e, e);
}
}
|
diff --git a/src/net/patuck/stegmpp/xmpp/Presence.java b/src/net/patuck/stegmpp/xmpp/Presence.java
index d2b88fc..a5019d0 100644
--- a/src/net/patuck/stegmpp/xmpp/Presence.java
+++ b/src/net/patuck/stegmpp/xmpp/Presence.java
@@ -1,59 +1,59 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.patuck.stegmpp.xmpp;
import java.io.PrintWriter;
import net.patuck.stegmpp.StegMPP;
import net.patuck.stegmpp.ui.Style;
/**
* The presence class handles presence objects.
* @author reshad
*/
public class Presence
{
private static PrintWriter pw=null;
/**
* Set the PrintWriter to write to the XMPP server.
* @param p the PrintWriter object.
*/
public static void setPrintWriter(PrintWriter p)
{
pw = p;
}
public static void sendPresence()
{
}
public static void receivePresence(org.jdom2.Document tag)
{
if(tag.getRootElement().getAttribute("from") != null)
{
String from = tag.getRootElement().getAttribute("from").getValue();
if(from.substring(0, from.indexOf('/')).trim().equals(Session.to.trim()))
{
StegMPP.getUI().print("[System] ",Style.SYSTEM);
if(tag.getRootElement().getChildText("show") != null)
{
StegMPP.getUI().println(Session.to + " Online");
}
else if(tag.getRootElement().getAttributeValue("type") != null )
{
if(tag.getRootElement().getAttributeValue("type").equals("unavailable") )
{
- StegMPP.getUI().println(Session.to + " Online");
+ StegMPP.getUI().println(Session.to + " Offline");
}
}
}
}
}
}
| true | true | public static void receivePresence(org.jdom2.Document tag)
{
if(tag.getRootElement().getAttribute("from") != null)
{
String from = tag.getRootElement().getAttribute("from").getValue();
if(from.substring(0, from.indexOf('/')).trim().equals(Session.to.trim()))
{
StegMPP.getUI().print("[System] ",Style.SYSTEM);
if(tag.getRootElement().getChildText("show") != null)
{
StegMPP.getUI().println(Session.to + " Online");
}
else if(tag.getRootElement().getAttributeValue("type") != null )
{
if(tag.getRootElement().getAttributeValue("type").equals("unavailable") )
{
StegMPP.getUI().println(Session.to + " Online");
}
}
}
}
}
| public static void receivePresence(org.jdom2.Document tag)
{
if(tag.getRootElement().getAttribute("from") != null)
{
String from = tag.getRootElement().getAttribute("from").getValue();
if(from.substring(0, from.indexOf('/')).trim().equals(Session.to.trim()))
{
StegMPP.getUI().print("[System] ",Style.SYSTEM);
if(tag.getRootElement().getChildText("show") != null)
{
StegMPP.getUI().println(Session.to + " Online");
}
else if(tag.getRootElement().getAttributeValue("type") != null )
{
if(tag.getRootElement().getAttributeValue("type").equals("unavailable") )
{
StegMPP.getUI().println(Session.to + " Offline");
}
}
}
}
}
|
diff --git a/src/main/battlecode/engine/RobotRunnable.java b/src/main/battlecode/engine/RobotRunnable.java
index 50127947..4e34efd3 100644
--- a/src/main/battlecode/engine/RobotRunnable.java
+++ b/src/main/battlecode/engine/RobotRunnable.java
@@ -1,81 +1,81 @@
package battlecode.engine;
import java.lang.Runnable;
import java.lang.reflect.*;
import battlecode.engine.instrumenter.RobotDeathException;
import battlecode.engine.instrumenter.RobotMonitor;
/*
RobotRunnable is a wrapper for a player's main class. It is basically a Runnable, whose run method both instantiates the player's
main class and runs the player's run method.
TODO:
- better commenting
- better error reporting
*/
class RobotRunnable implements Runnable {
private final Class<?> myPlayerClass;
private final GenericController myRobotController;
public RobotRunnable(Class playerClass, GenericController rc) {
myPlayerClass = playerClass;
myRobotController = rc;
}
// instantiates the class passed to the RobotRunnable constructor, and runs its run method
public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
- if (t.getCause() instanceof RobotDeathException)
+ if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
}
| true | true | public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
| public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
|
diff --git a/src/main/java/RedPointMaven/Roster.java b/src/main/java/RedPointMaven/Roster.java
index c9105c6..9cae57b 100644
--- a/src/main/java/RedPointMaven/Roster.java
+++ b/src/main/java/RedPointMaven/Roster.java
@@ -1,109 +1,109 @@
package RedPointMaven;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;
public class Roster {
//use a TreeMap to order roster_list alphabetically by key
TreeMap<String, Player> roster_list;
private Set<String> playerCodeKeySet;
public Roster() {
roster_list = new TreeMap<String, Player>();
roster_list.put("AdaBur", new Player("Adam Burish", "DunKei"));
roster_list.put("AndLad", new Player("Andrew Ladd", "JoeQue"));
roster_list.put("AntNie", new Player("Antti Niemi", "JonToe"));
roster_list.put("BreSea", new Player("Brent Seabrook", "KriVer"));
roster_list.put("BryBic", new Player("Bryan Bickell", "MarHos"));
roster_list.put("BriCam", new Player("Brian Campbell", "NikHja"));
roster_list.put("CriHue", new Player("Cristobal Huet", "PatKan"));
roster_list.put("DavBol", new Player("Dave Bolland", "PatSha"));
roster_list.put("DunKei", new Player("Duncan Keith", "TomKop"));
roster_list.put("JoeQue", new Player("Joel Quenneville", "TroBro"));
roster_list.put("JonToe", new Player("Jonathan Toews", "AdaBur"));
roster_list.put("KriVer", new Player("Kris Versteeg", "AndLad"));
roster_list.put("MarHos", new Player("Marian Hossa", "AntNie"));
roster_list.put("NikHja", new Player("Niklas Hjalmarsson", "BreSea"));
roster_list.put("PatKan", new Player("Patrick Kane", "BryBic"));
roster_list.put("PatSha", new Player("Patrick Sharp", "BriCam"));
roster_list.put("TomKop", new Player("Tomas Kopecky", "CriHue"));
roster_list.put("TroBro", new Player("Troy Brouwer", "DavBol"));
}
//inner class
private class Player {
String playerName;
ArrayList<String> pastGiveesCodes;
private Player(String playerName, String giveeCodeYearZero) {
this.playerName = playerName;
pastGiveesCodes = new ArrayList<String>();
pastGiveesCodes.add(0, giveeCodeYearZero);
}
//return playerName
private String getPlayerName() {
return playerName;
}
//add a giveeCode to array of past givees
private boolean addGiveeCode(String giveeCode) {
return pastGiveesCodes.add(giveeCode);
}
//return a giveeCode given a year
private String returnGiveeCode(int giftYear) {
return pastGiveesCodes.get(giftYear);
}
//set a giveeCode in a given year
private String setGiveeCode(String giveeCode, int year) {
return pastGiveesCodes.set(year, giveeCode);
}
}
private Player returnPlayer(String playerCode) {
return roster_list.get(playerCode);
}
public String setGiveeCode(String playerCode, String giveeCode, int year) {
return this.returnPlayer(playerCode).setGiveeCode(giveeCode, year);
}
public String returnGiveeCode(String playerCode, int year) {
return this.returnPlayer(playerCode).returnGiveeCode(year);
}
//add a new empty year ("none") to each Player's givee array
public void addNewYear() {
playerCodeKeySet = roster_list.keySet();
for (String aKey : playerCodeKeySet) {
this.returnPlayer(aKey).addGiveeCode("none");
}
}
public void printGivingRoster(int year) {
/*
uses key:value pair functionality of keySet.
returns a msg if no match (playerCode = "none")
where last giver/givee in Hats fail a test.
*/
String playerName;
String giveeCode;
String giveeName;
playerCodeKeySet = roster_list.keySet();
for (String aKey : playerCodeKeySet) {
playerName = this.returnPlayer(aKey).getPlayerName();
giveeCode = this.returnPlayer(aKey).returnGiveeCode(year);
if (giveeCode.equals("none")) {
giveeName = "...nobody!! (last giver/givee pairing and a test failed - a puzzle logic error)";
} else {
- giveeName = this.returnPlayer(aKey).getPlayerName();
+ giveeName = this.returnPlayer(giveeCode).playerName;
}
System.out.println(playerName + " is buying for " + giveeName);
}
}
}
| true | true | public void printGivingRoster(int year) {
/*
uses key:value pair functionality of keySet.
returns a msg if no match (playerCode = "none")
where last giver/givee in Hats fail a test.
*/
String playerName;
String giveeCode;
String giveeName;
playerCodeKeySet = roster_list.keySet();
for (String aKey : playerCodeKeySet) {
playerName = this.returnPlayer(aKey).getPlayerName();
giveeCode = this.returnPlayer(aKey).returnGiveeCode(year);
if (giveeCode.equals("none")) {
giveeName = "...nobody!! (last giver/givee pairing and a test failed - a puzzle logic error)";
} else {
giveeName = this.returnPlayer(aKey).getPlayerName();
}
System.out.println(playerName + " is buying for " + giveeName);
}
}
| public void printGivingRoster(int year) {
/*
uses key:value pair functionality of keySet.
returns a msg if no match (playerCode = "none")
where last giver/givee in Hats fail a test.
*/
String playerName;
String giveeCode;
String giveeName;
playerCodeKeySet = roster_list.keySet();
for (String aKey : playerCodeKeySet) {
playerName = this.returnPlayer(aKey).getPlayerName();
giveeCode = this.returnPlayer(aKey).returnGiveeCode(year);
if (giveeCode.equals("none")) {
giveeName = "...nobody!! (last giver/givee pairing and a test failed - a puzzle logic error)";
} else {
giveeName = this.returnPlayer(giveeCode).playerName;
}
System.out.println(playerName + " is buying for " + giveeName);
}
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/JsCompiler.java b/src/main/java/com/redhat/ceylon/compiler/js/JsCompiler.java
index 8772eb30..b179a0af 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/JsCompiler.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/JsCompiler.java
@@ -1,408 +1,408 @@
package com.redhat.ceylon.compiler.js;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.minidev.json.JSONObject;
import com.redhat.ceylon.cmr.api.ArtifactContext;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.api.SourceArchiveCreator;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.impl.JULLogger;
import com.redhat.ceylon.cmr.impl.ShaSigner;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.Unit;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
public class JsCompiler {
protected final TypeChecker tc;
protected final Options opts;
protected final RepositoryManager outRepo;
private boolean stopOnErrors = true;
private int errCount = 0;
protected Set<Message> errors = new HashSet<Message>();
protected Set<Message> unitErrors = new HashSet<Message>();
protected List<String> files;
private final Map<Module, JsOutput> output = new HashMap<Module, JsOutput>();
//You have to manually set this when compiling the language module
static boolean compilingLanguageModule;
private TypeUtils types;
private final Visitor unitVisitor = new Visitor() {
private boolean hasErrors(Node that) {
for (Message m: that.getErrors()) {
if (m instanceof AnalysisError) {
return true;
}
}
return false;
}
@Override
public void visitAny(Node that) {
super.visitAny(that);
for (Message err: that.getErrors()) {
unitErrors.add(err);
}
}
@Override
public void visit(Tree.ImportMemberOrType that) {
if (hasErrors(that)) return;
Unit u = that.getImportModel().getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| u.getPackage().getModule().isJava()) {
that.addUnexpectedError("cannot import Java declarations in Javascript");
}
super.visit(that);
}
@Override
public void visit(Tree.ImportModule that) {
if (hasErrors(that)) return;
if (((Module)that.getImportPath().getModel()).isJava()) {
that.getImportPath().addUnexpectedError("cannot import Java modules in Javascript");
}
super.visit(that);
}
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava())) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
@Override
public void visit(Tree.QualifiedMemberOrTypeExpression that) {
if (hasErrors(that)) return;
if (that.getDeclaration() != null && that.getDeclaration().getUnit() != null) {
Unit u = that.getDeclaration().getUnit();
if ((u.getFilename() != null && !u.getFilename().endsWith(".ceylon"))
|| (u.getPackage() != null && u.getPackage().getModule() != null && u.getPackage().getModule().isJava())) {
that.addUnexpectedError("cannot call Java declarations in Javascript");
}
}
super.visit(that);
}
};
public JsCompiler(TypeChecker tc, Options options) {
this.tc = tc;
opts = options;
outRepo = CeylonUtils.repoManager()
.outRepo(options.getOutDir())
.user(options.getUser())
.password(options.getPass())
.buildOutputManager();
String outDir = options.getOutDir();
if(!isURL(outDir)){
File root = new File(outDir);
if (root.exists()) {
if (!(root.isDirectory() && root.canWrite())) {
System.err.printf("Cannot write to %s. Stop.%n", root);
}
} else {
if (!root.mkdirs()) {
System.err.printf("Cannot create %s. Stop.%n", root);
}
}
}
types = new TypeUtils(tc.getContext().getModules().getLanguageModule());
}
private boolean isURL(String path) {
try {
new URL(path);
return true;
} catch (MalformedURLException e) {
return false;
}
}
/** Specifies whether the compiler should stop when errors are found in a compilation unit (default true). */
public JsCompiler stopOnErrors(boolean flag) {
stopOnErrors = flag;
return this;
}
/** Sets the names of the files to compile. By default this is null, which means all units from the typechecker
* will be compiled. */
public void setFiles(List<String> files) {
this.files = files;
}
public Set<Message> listErrors() {
return getErrors();
}
/** Compile one phased unit.
* @return The errors found for the unit. */
public Set<Message> compileUnit(PhasedUnit pu, JsIdentifierNames names) throws IOException {
unitErrors.clear();
pu.getCompilationUnit().visit(unitVisitor);
if (errCount == 0 || !stopOnErrors) {
if (opts.isVerbose()) {
System.out.printf("%nCompiling %s to JS%n", pu.getUnitFile().getPath());
}
//Perform capture analysis
for (com.redhat.ceylon.compiler.typechecker.model.Declaration d : pu.getDeclarations()) {
if (d instanceof TypedDeclaration && d instanceof com.redhat.ceylon.compiler.typechecker.model.Setter == false) {
pu.getCompilationUnit().visit(new ValueVisitor((TypedDeclaration)d));
}
}
JsOutput jsout = getOutput(pu);
GenerateJsVisitor jsv = new GenerateJsVisitor(jsout, opts, names, pu.getTokens(), types);
pu.getCompilationUnit().visit(jsv);
pu.getCompilationUnit().visit(unitVisitor);
}
return unitErrors;
}
/** Indicates if compilation should stop, based on whether there were errors
* in the last compilation unit and the stopOnErrors flag is set. */
protected boolean stopOnError() {
for (Message err : unitErrors) {
if (err instanceof AnalysisError ||
err instanceof UnexpectedError) {
errCount++;
}
errors.add(err);
}
return stopOnErrors && errCount > 0;
}
/** Compile all the phased units in the typechecker.
* @return true is compilation was successful (0 errors/warnings), false otherwise. */
public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
System.out.println("Generating metamodel...");
}
//First generate the metamodel
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.isVerbose()) {
System.out.println(pu.getCompilationUnit());
}
}
}
//Then write it out
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().getWriter().write("var $$METAMODEL$$=");
e.getValue().getWriter().write(JSONObject.toJSONString(e.getValue().mmg.getModel()));
e.getValue().getWriter().write(";\nexports.$$METAMODEL$$=function(){return $$METAMODEL$$;};\n");
}
}
//Then generate the JS code
JsIdentifierNames names = new JsIdentifierNames();
if (files == null) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
} else {
if (opts.isVerbose()) {
System.err.println("Files does not contain "+path);
for (String p : files) {
System.err.println(" Files: "+p);
}
}
}
}
} else if(!tc.getPhasedUnits().getPhasedUnits().isEmpty()){
final List<PhasedUnit> units = tc.getPhasedUnits().getPhasedUnits();
PhasedUnit lastUnit = units.get(0);
for (String path : files) {
if (path.endsWith(".js")) {
//Just output the file
File f = new File(path);
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
String line = null;
while ((line = reader.readLine()) != null) {
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : units) {
- String unitPath = pu.getUnitFile().getPath().replace('/', File.separatorChar);
+ String unitPath = pu.getUnitFile().getPath();
if (path.equals(unitPath)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
lastUnit = pu;
}
}
}
}
}else{
System.err.println("No source units found to compile");
}
} finally {
finish();
}
return errCount == 0;
}
/** Creates a JsOutput if needed, for the PhasedUnit.
* Right now it's one file per module. */
private JsOutput getOutput(PhasedUnit pu) throws IOException {
Module mod = pu.getPackage().getModule();
JsOutput jsout = output.get(mod);
if (jsout==null) {
jsout = newJsOutput(mod);
output.put(mod, jsout);
if (opts.isModulify()) {
beginWrapper(jsout.getWriter());
}
}
return jsout;
}
/** This exists solely so that the web IDE can override it and use a different JsOutput */
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsOutput(m, opts.getEncoding());
}
/** Closes all output writers and puts resulting artifacts in the output repo. */
protected void finish() throws IOException {
for (Map.Entry<Module,JsOutput> entry: output.entrySet()) {
JsOutput jsout = entry.getValue();
if (opts.isModulify()) {
endWrapper(jsout.getWriter());
}
String moduleName = entry.getKey().getNameAsString();
String moduleVersion = entry.getKey().getVersion();
//Create the JS file
File jsart = entry.getValue().close();
ArtifactContext artifact = new ArtifactContext(moduleName, moduleVersion, ArtifactContext.JS);
if (entry.getKey().isDefault()) {
System.err.println("Created module "+moduleName);
} else {
System.err.println("Created module "+moduleName+"/"+moduleVersion);
}
outRepo.putArtifact(artifact, jsart);
//js file signature
artifact.setForceOperation(true);
ArtifactContext sha1Context = artifact.getSha1Context();
sha1Context.setForceOperation(true);
File sha1File = ShaSigner.sign(jsart, new JULLogger(), opts.isVerbose());
outRepo.putArtifact(sha1Context, sha1File);
//Create the src archive
if (opts.isGenerateSourceArchive()) {
Set<File> sourcePaths = new HashSet<File>();
for (String sp : opts.getSrcDirs()) {
sourcePaths.add(new File(sp));
}
SourceArchiveCreator sac = CeylonUtils.makeSourceArchiveCreator(outRepo, sourcePaths,
moduleName, moduleVersion, opts.isVerbose(), new JULLogger());
sac.copySourceFiles(jsout.getSources());
}
sha1File.deleteOnExit();
jsart.deleteOnExit();
}
}
/** Print all the errors found during compilation to the specified stream. */
public int printErrors(PrintStream out) {
int count = 0;
for (Message err: errors) {
if (err instanceof UsageWarning) {
out.print("warning");
} else {
out.print("error");
}
out.printf(" encountered [%s]", err.getMessage());
if (err instanceof AnalysisMessage) {
Node n = ((AnalysisMessage)err).getTreeNode();
out.printf(" at %s of %s", n.getLocation(), n.getUnit().getFilename());
} else if (err instanceof RecognitionError) {
RecognitionError rer = (RecognitionError)err;
out.printf(" at %d:%d", rer.getLine(), rer.getCharacterInLine());
}
out.println();
count++;
}
return count;
}
/** Returns the list of errors found during compilation. */
public Set<Message> getErrors() {
return Collections.unmodifiableSet(errors);
}
public void printErrorsAndCount(PrintStream out) {
int count = printErrors(out);
out.printf("%d errors.%n", count);
}
/** Writes the beginning of the wrapper function for a JS module. */
public void beginWrapper(Writer writer) throws IOException {
writer.write("(function(define) { define(function(require, exports, module) {\n");
}
/** Writes the ending of the wrapper function for a JS module. */
public void endWrapper(Writer writer) throws IOException {
//Finish the wrapper
writer.write("});\n");
writer.write("}(typeof define==='function' && define.amd ? define : function (factory) {\n");
writer.write("if (typeof exports!=='undefined') { factory(require, exports, module);\n");
writer.write("} else { throw 'no module loader'; }\n");
writer.write("}));\n");
}
/** Returns true if the compiler is currently compiling the language module. */
public static boolean isCompilingLanguageModule() {
return compilingLanguageModule;
}
}
| true | true | public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
System.out.println("Generating metamodel...");
}
//First generate the metamodel
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.isVerbose()) {
System.out.println(pu.getCompilationUnit());
}
}
}
//Then write it out
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().getWriter().write("var $$METAMODEL$$=");
e.getValue().getWriter().write(JSONObject.toJSONString(e.getValue().mmg.getModel()));
e.getValue().getWriter().write(";\nexports.$$METAMODEL$$=function(){return $$METAMODEL$$;};\n");
}
}
//Then generate the JS code
JsIdentifierNames names = new JsIdentifierNames();
if (files == null) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
} else {
if (opts.isVerbose()) {
System.err.println("Files does not contain "+path);
for (String p : files) {
System.err.println(" Files: "+p);
}
}
}
}
} else if(!tc.getPhasedUnits().getPhasedUnits().isEmpty()){
final List<PhasedUnit> units = tc.getPhasedUnits().getPhasedUnits();
PhasedUnit lastUnit = units.get(0);
for (String path : files) {
if (path.endsWith(".js")) {
//Just output the file
File f = new File(path);
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
String line = null;
while ((line = reader.readLine()) != null) {
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : units) {
String unitPath = pu.getUnitFile().getPath().replace('/', File.separatorChar);
if (path.equals(unitPath)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
lastUnit = pu;
}
}
}
}
}else{
System.err.println("No source units found to compile");
}
} finally {
finish();
}
return errCount == 0;
}
| public boolean generate() throws IOException {
errors.clear();
errCount = 0;
output.clear();
try {
if (opts.isVerbose()) {
System.out.println("Generating metamodel...");
}
//First generate the metamodel
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
pu.getCompilationUnit().visit(getOutput(pu).mmg);
if (opts.isVerbose()) {
System.out.println(pu.getCompilationUnit());
}
}
}
//Then write it out
if (!compilingLanguageModule) {
for (Map.Entry<Module,JsOutput> e : output.entrySet()) {
e.getValue().getWriter().write("var $$METAMODEL$$=");
e.getValue().getWriter().write(JSONObject.toJSONString(e.getValue().mmg.getModel()));
e.getValue().getWriter().write(";\nexports.$$METAMODEL$$=function(){return $$METAMODEL$$;};\n");
}
}
//Then generate the JS code
JsIdentifierNames names = new JsIdentifierNames();
if (files == null) {
for (PhasedUnit pu: tc.getPhasedUnits().getPhasedUnits()) {
String path = pu.getUnitFile().getPath();
if (files == null || files.contains(path)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
} else {
if (opts.isVerbose()) {
System.err.println("Files does not contain "+path);
for (String p : files) {
System.err.println(" Files: "+p);
}
}
}
}
} else if(!tc.getPhasedUnits().getPhasedUnits().isEmpty()){
final List<PhasedUnit> units = tc.getPhasedUnits().getPhasedUnits();
PhasedUnit lastUnit = units.get(0);
for (String path : files) {
if (path.endsWith(".js")) {
//Just output the file
File f = new File(path);
final JsOutput lastOut = getOutput(lastUnit);
try (BufferedReader reader = new BufferedReader(new FileReader(f))) {
String line = null;
while ((line = reader.readLine()) != null) {
lastOut.getWriter().write(line);
lastOut.getWriter().write('\n');
}
} finally {
lastOut.addSource(path);
}
} else {
//Find the corresponding compilation unit
for (PhasedUnit pu : units) {
String unitPath = pu.getUnitFile().getPath();
if (path.equals(unitPath)) {
compileUnit(pu, names);
if (stopOnError()) {
System.err.println("Errors found. Compilation stopped.");
break;
}
getOutput(pu).addSource(pu.getUnit().getFullPath());
lastUnit = pu;
}
}
}
}
}else{
System.err.println("No source units found to compile");
}
} finally {
finish();
}
return errCount == 0;
}
|
diff --git a/src/Accounts/MailManager.java b/src/Accounts/MailManager.java
index e496a9d..06d480c 100755
--- a/src/Accounts/MailManager.java
+++ b/src/Accounts/MailManager.java
@@ -1,140 +1,140 @@
package Accounts;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import Servlets.MyDB;
import com.mysql.jdbc.Statement;
public class MailManager {
private static Connection con;
public MailManager(Connection con) {
this.con = con;//Servlets.MyDB.getConnection();
}
public boolean sendMessage(Message mail) {
Statement stmt;
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO message VALUES (default, \"");
sb.append(mail.getSender());
sb.append("\", \"");
sb.append(mail.getRecipient());
sb.append("\", \"");
sb.append(mail.getSubject());
sb.append("\", \"");
sb.append(mail.getBody());
sb.append("\", \"");
sb.append(new Timestamp(mail.getTimestamp()));
sb.append("\", ");
if (mail.getChallengeID() > 0) {
sb.append(mail.getChallengeID());
} else {
sb.append("default");
}
- sb.append(");");
+ sb.append(", default);");
try {
System.out.println(sb.toString());
stmt = (Statement) con.createStatement();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
public Message recieveMessage(int id) {
ResultSet rs;
Statement stmt;
Message m = null;
try {
stmt = (Statement) con.createStatement();
rs = stmt.executeQuery("select * from message where message_id = " + id + ";");
if(rs.next()) {
String sender = rs.getString("sender");
String recipient = rs.getString("recipient");
String subject = rs.getString("subject");
String body = rs.getString("message");
Date time = rs.getTimestamp("date");
int challengeID = rs.getInt("quiz_id");
String challengeName = null;
if (challengeID > 0) {
rs = stmt.executeQuery("select name from quiz where quiz_id = " + challengeID + ";");
if (rs.next()) challengeName = rs.getString("name");
}
m = new Message(sender, recipient, subject, body, time.getTime(), challengeID, challengeName);
stmt.executeUpdate("update message set unread = false where message_id = "+id);
}
} catch (SQLException e) {
e.printStackTrace();
}
return m;
}
public int getUnread(Account acct) {
int newMessages = 0;
Statement stmt;
ResultSet rs;
try {
stmt = (Statement) con.createStatement();
rs = stmt.executeQuery("select count(*) from message where recipient = \"" + acct.getName() + "\" and unread = true;");
if(rs.next()) newMessages = rs.getInt("count(*)");
} catch (SQLException e) {
e.printStackTrace();
}
return newMessages;
}
public HashMap<Integer, Message> listInbox(String recipient) {
ResultSet rs;
Statement stmt;
HashMap<Integer,Message> inbox = null;
try {
inbox = new HashMap<Integer,Message>();
stmt = (Statement) con.createStatement();
rs = stmt.executeQuery("select message_id, sender, subject, date from message where recipient = \"" + recipient + "\"");
while (rs.next()) {
Integer key = rs.getInt("message_ID");
String sender = rs.getString("sender");
String subject = rs.getString("subject");
Date time = rs.getTimestamp("date");
inbox.put(key, new Message(sender, recipient, subject, null, time.getTime(), 0, null));
}
} catch (SQLException e) {
e.printStackTrace();
}
return inbox;
}
public HashMap<Integer, Message> listOutbox(String sender) {
ResultSet rs;
Statement stmt;
HashMap<Integer,Message> outbox = null;
try {
outbox = new HashMap<Integer,Message>();
stmt = (Statement) con.createStatement();
rs = stmt.executeQuery("select message_id, recipient, subject, date from message where sender = \"" + sender + "\"");
while (rs.next()) {
Integer key = rs.getInt("message_ID");
String recipient = rs.getString("recipient");
String subject = rs.getString("subject");
Date time = rs.getTimestamp("date");
outbox.put(key, new Message(sender, recipient, subject, null, time.getTime(), 0, null));
}
} catch (SQLException e) {
e.printStackTrace();
}
return outbox;
}
}
| true | true | public boolean sendMessage(Message mail) {
Statement stmt;
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO message VALUES (default, \"");
sb.append(mail.getSender());
sb.append("\", \"");
sb.append(mail.getRecipient());
sb.append("\", \"");
sb.append(mail.getSubject());
sb.append("\", \"");
sb.append(mail.getBody());
sb.append("\", \"");
sb.append(new Timestamp(mail.getTimestamp()));
sb.append("\", ");
if (mail.getChallengeID() > 0) {
sb.append(mail.getChallengeID());
} else {
sb.append("default");
}
sb.append(");");
try {
System.out.println(sb.toString());
stmt = (Statement) con.createStatement();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
| public boolean sendMessage(Message mail) {
Statement stmt;
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO message VALUES (default, \"");
sb.append(mail.getSender());
sb.append("\", \"");
sb.append(mail.getRecipient());
sb.append("\", \"");
sb.append(mail.getSubject());
sb.append("\", \"");
sb.append(mail.getBody());
sb.append("\", \"");
sb.append(new Timestamp(mail.getTimestamp()));
sb.append("\", ");
if (mail.getChallengeID() > 0) {
sb.append(mail.getChallengeID());
} else {
sb.append("default");
}
sb.append(", default);");
try {
System.out.println(sb.toString());
stmt = (Statement) con.createStatement();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return true;
}
|
diff --git a/src/com/livegameengine/web/GameServlet.java b/src/com/livegameengine/web/GameServlet.java
index c048fd6..7e2cebd 100644
--- a/src/com/livegameengine/web/GameServlet.java
+++ b/src/com/livegameengine/web/GameServlet.java
@@ -1,377 +1,378 @@
package com.livegameengine.web;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Node;
import org.xml.sax.helpers.XMLReaderFactory;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.utils.SystemProperty;
import com.livegameengine.config.Config;
import com.livegameengine.error.GameLoadException;
import com.livegameengine.model.ClientMessage;
import com.livegameengine.model.Game;
import com.livegameengine.model.GameState;
import com.livegameengine.model.GameType;
import com.livegameengine.model.GameURIResolver;
import com.livegameengine.model.GameUser;
import com.livegameengine.model.Player;
import com.livegameengine.model.Watcher;
import com.livegameengine.persist.PMF;
import com.livegameengine.util.AddListenersParser;
import com.livegameengine.util.Util;
import com.sun.org.apache.xerces.internal.dom.DocumentTypeImpl;
import com.sun.xml.internal.fastinfoset.stax.util.StAXParserWrapper;
public class GameServlet extends HttpServlet {
Log log = LogFactory.getLog(GameServlet.class);
Config config = Config.getInstance();
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
handleRequest(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
handleRequest(req, resp);
}
public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User u = userService.getCurrentUser();
GameUser gu = GameUser.findOrCreateGameUserByUser(u);
Pattern p = Pattern.compile("/-/([^/]+)/(meta|data|raw_view|join|start|addListeners|message|(event/([^/]+)))?");
final Matcher m = p.matcher(req.getPathInfo());
//log.info("path info: " + req.getPathInfo());
if(m != null && m.matches()) {
Game g;
try {
g = Game.findGameByKey(KeyFactory.stringToKey(m.group(1)));
} catch (GameLoadException e1) {
g = null;
}
if(g == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game not found: " + m.group(1));
return;
}
GameState gs = g.getMostRecentState();
if(gs == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game has no recent state: " + m.group(1));
return;
}
Document doc = null;
Document doc1 = null;
doc = config.newXmlDocument();
doc1 = config.newXmlDocument();
OutputStream responseStream = resp.getOutputStream();
StreamResult responseResult = new StreamResult(responseStream);
if(m.group(2) == null) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
resp.setContentType("application/xhtml+xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("raw_view")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Raw");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("data")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Data");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("meta")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
XMLOutputFactory factory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = factory.createXMLStreamWriter(responseStream, config.getEncoding());
writer.setDefaultNamespace(config.getGameEngineNamespace());
writer.writeStartDocument();
g.serializeToXml("game", writer);
writer.writeEndDocument();
writer.flush();
} catch (XMLStreamException e) {
resp.setStatus(500);
e.printStackTrace();
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("addListeners")) {
/*
Document d = config.newXmlDocument();
Transformer t = null;
try {
t = config.newTransformer();
t.transform(new StreamSource(req.getInputStream()), new DOMResult(d));
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
// invalid xml input
resp.setStatus(400);
e.printStackTrace();
}
*/
Set<String> listeners = parseAddListenersRequest(req);
Watcher w = Watcher.findWatcherByGameAndGameUser(g, gu);
if(w != null) {
w.addListners(listeners);
}
}
else if(m.group(2).equals("message")) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
String since = req.getParameter("since");
if(since == null) {
resp.setStatus(400);
return;
}
Date s;
try {
s = config.getDateFormat().parse(since);
} catch (ParseException e) {
resp.setStatus(400);
return;
}
+ log.info(String.format("since: %s, parsed: %s", since, config.getDateFormat().format(s)));
List<ClientMessage> messages = ClientMessage.findClientMessagesSince(g, s);
if(messages == null || messages.size() == 0) {
resp.setStatus(204);
return;
}
ClientMessageSource so = new ClientMessageSource(messages);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "View");
try {
gametrans.transform(so, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("start") || m.group(2).equals("join") || m.group(2).startsWith("event/")) {
if(!req.getMethod().equals("POST")) {
resp.setStatus(405);
resp.addHeader("Allow", "POST");
return;
}
if(u == null) {
resp.setStatus(403);
return;
}
boolean success = true;
if(m.group(2).equals("start")) {
success = g.sendStartGameRequest(u);
}
else if(m.group(2).equals("join")) {
success = g.sendPlayerJoinRequest(u);
}
else if(m.group(2).startsWith("event/")) {
String eventName = "board." + m.group(4);
Node data = doc.createElementNS(config.getGameEngineNamespace(), "data");
Node player = doc.createElementNS(config.getGameEngineNamespace(), "player");
player.appendChild(doc.createTextNode(gu.getHashedUserId()));
data.appendChild(player);
doc.appendChild(data);
DOMResult dr = new DOMResult(data);
if(req.getContentLength() > 0) {
try {
Transformer trans = config.newTransformer();
trans.transform(new StreamSource(req.getInputStream()), dr);
} catch (TransformerException e) {
// ignore error
}
}
success = g.triggerEvent(eventName, data);
}
if(!success) {
String errorMessage = "";
if(!g.isError()) {
// there was no official error, the event is simply not valid
errorMessage = "Action not valid in the current game state";
}
else {
errorMessage = g.getErrorMessage();
}
Node error = doc1.createElementNS(config.getGameEngineNamespace(), "error");
error.appendChild(doc1.createTextNode(errorMessage));
doc1.appendChild(error);
resp.setContentType("application/xml");
resp.setStatus(400);
Transformer trans;
try {
trans = config.newTransformer();
trans.transform(new DOMSource(doc1), responseResult);
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
resp.setStatus(500);
e.printStackTrace();
}
g.clearError();
}
else {
resp.setStatus(200);
}
}
else {
resp.setStatus(404);
resp.setContentType("text/plain");
//resp.getWriter().write("unknown url");
}
}
else {
resp.setStatus(404);
resp.getWriter().write("game not found.");
}
}
private Set<String> parseAddListenersRequest(HttpServletRequest req) throws IOException {
AddListenersParser alp;
try {
alp = new AddListenersParser(req);
} catch (XMLStreamException e) {
throw new IOException("parser error.");
}
return alp.getEvents();
}
}
| true | true | public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User u = userService.getCurrentUser();
GameUser gu = GameUser.findOrCreateGameUserByUser(u);
Pattern p = Pattern.compile("/-/([^/]+)/(meta|data|raw_view|join|start|addListeners|message|(event/([^/]+)))?");
final Matcher m = p.matcher(req.getPathInfo());
//log.info("path info: " + req.getPathInfo());
if(m != null && m.matches()) {
Game g;
try {
g = Game.findGameByKey(KeyFactory.stringToKey(m.group(1)));
} catch (GameLoadException e1) {
g = null;
}
if(g == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game not found: " + m.group(1));
return;
}
GameState gs = g.getMostRecentState();
if(gs == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game has no recent state: " + m.group(1));
return;
}
Document doc = null;
Document doc1 = null;
doc = config.newXmlDocument();
doc1 = config.newXmlDocument();
OutputStream responseStream = resp.getOutputStream();
StreamResult responseResult = new StreamResult(responseStream);
if(m.group(2) == null) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
resp.setContentType("application/xhtml+xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("raw_view")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Raw");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("data")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Data");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("meta")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
XMLOutputFactory factory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = factory.createXMLStreamWriter(responseStream, config.getEncoding());
writer.setDefaultNamespace(config.getGameEngineNamespace());
writer.writeStartDocument();
g.serializeToXml("game", writer);
writer.writeEndDocument();
writer.flush();
} catch (XMLStreamException e) {
resp.setStatus(500);
e.printStackTrace();
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("addListeners")) {
/*
Document d = config.newXmlDocument();
Transformer t = null;
try {
t = config.newTransformer();
t.transform(new StreamSource(req.getInputStream()), new DOMResult(d));
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
// invalid xml input
resp.setStatus(400);
e.printStackTrace();
}
*/
Set<String> listeners = parseAddListenersRequest(req);
Watcher w = Watcher.findWatcherByGameAndGameUser(g, gu);
if(w != null) {
w.addListners(listeners);
}
}
else if(m.group(2).equals("message")) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
String since = req.getParameter("since");
if(since == null) {
resp.setStatus(400);
return;
}
Date s;
try {
s = config.getDateFormat().parse(since);
} catch (ParseException e) {
resp.setStatus(400);
return;
}
List<ClientMessage> messages = ClientMessage.findClientMessagesSince(g, s);
if(messages == null || messages.size() == 0) {
resp.setStatus(204);
return;
}
ClientMessageSource so = new ClientMessageSource(messages);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "View");
try {
gametrans.transform(so, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("start") || m.group(2).equals("join") || m.group(2).startsWith("event/")) {
if(!req.getMethod().equals("POST")) {
resp.setStatus(405);
resp.addHeader("Allow", "POST");
return;
}
if(u == null) {
resp.setStatus(403);
return;
}
boolean success = true;
if(m.group(2).equals("start")) {
success = g.sendStartGameRequest(u);
}
else if(m.group(2).equals("join")) {
success = g.sendPlayerJoinRequest(u);
}
else if(m.group(2).startsWith("event/")) {
String eventName = "board." + m.group(4);
Node data = doc.createElementNS(config.getGameEngineNamespace(), "data");
Node player = doc.createElementNS(config.getGameEngineNamespace(), "player");
player.appendChild(doc.createTextNode(gu.getHashedUserId()));
data.appendChild(player);
doc.appendChild(data);
DOMResult dr = new DOMResult(data);
if(req.getContentLength() > 0) {
try {
Transformer trans = config.newTransformer();
trans.transform(new StreamSource(req.getInputStream()), dr);
} catch (TransformerException e) {
// ignore error
}
}
success = g.triggerEvent(eventName, data);
}
if(!success) {
String errorMessage = "";
if(!g.isError()) {
// there was no official error, the event is simply not valid
errorMessage = "Action not valid in the current game state";
}
else {
errorMessage = g.getErrorMessage();
}
Node error = doc1.createElementNS(config.getGameEngineNamespace(), "error");
error.appendChild(doc1.createTextNode(errorMessage));
doc1.appendChild(error);
resp.setContentType("application/xml");
resp.setStatus(400);
Transformer trans;
try {
trans = config.newTransformer();
trans.transform(new DOMSource(doc1), responseResult);
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
resp.setStatus(500);
e.printStackTrace();
}
g.clearError();
}
else {
resp.setStatus(200);
}
}
else {
resp.setStatus(404);
resp.setContentType("text/plain");
//resp.getWriter().write("unknown url");
}
}
else {
resp.setStatus(404);
resp.getWriter().write("game not found.");
}
}
| public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User u = userService.getCurrentUser();
GameUser gu = GameUser.findOrCreateGameUserByUser(u);
Pattern p = Pattern.compile("/-/([^/]+)/(meta|data|raw_view|join|start|addListeners|message|(event/([^/]+)))?");
final Matcher m = p.matcher(req.getPathInfo());
//log.info("path info: " + req.getPathInfo());
if(m != null && m.matches()) {
Game g;
try {
g = Game.findGameByKey(KeyFactory.stringToKey(m.group(1)));
} catch (GameLoadException e1) {
g = null;
}
if(g == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game not found: " + m.group(1));
return;
}
GameState gs = g.getMostRecentState();
if(gs == null) {
resp.setStatus(404);
resp.setContentType("text/plain");
resp.getWriter().write("game has no recent state: " + m.group(1));
return;
}
Document doc = null;
Document doc1 = null;
doc = config.newXmlDocument();
doc1 = config.newXmlDocument();
OutputStream responseStream = resp.getOutputStream();
StreamResult responseResult = new StreamResult(responseStream);
if(m.group(2) == null) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
resp.setContentType("application/xhtml+xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("raw_view")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Raw");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("data")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
GameSource s = new GameSource(gs);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "Data");
try {
gametrans.transform(s, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("meta")) {
if(req.getMethod().equals("GET")) {
resp.setContentType("text/xml");
XMLOutputFactory factory = XMLOutputFactory.newFactory();
XMLStreamWriter writer = null;
try {
writer = factory.createXMLStreamWriter(responseStream, config.getEncoding());
writer.setDefaultNamespace(config.getGameEngineNamespace());
writer.writeStartDocument();
g.serializeToXml("game", writer);
writer.writeEndDocument();
writer.flush();
} catch (XMLStreamException e) {
resp.setStatus(500);
e.printStackTrace();
}
}
else {
resp.setStatus(405);
}
}
else if(m.group(2).equals("addListeners")) {
/*
Document d = config.newXmlDocument();
Transformer t = null;
try {
t = config.newTransformer();
t.transform(new StreamSource(req.getInputStream()), new DOMResult(d));
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
// invalid xml input
resp.setStatus(400);
e.printStackTrace();
}
*/
Set<String> listeners = parseAddListenersRequest(req);
Watcher w = Watcher.findWatcherByGameAndGameUser(g, gu);
if(w != null) {
w.addListners(listeners);
}
}
else if(m.group(2).equals("message")) {
if(!req.getMethod().equals("GET")) {
resp.setStatus(405);
return;
}
String since = req.getParameter("since");
if(since == null) {
resp.setStatus(400);
return;
}
Date s;
try {
s = config.getDateFormat().parse(since);
} catch (ParseException e) {
resp.setStatus(400);
return;
}
log.info(String.format("since: %s, parsed: %s", since, config.getDateFormat().format(s)));
List<ClientMessage> messages = ClientMessage.findClientMessagesSince(g, s);
if(messages == null || messages.size() == 0) {
resp.setStatus(204);
return;
}
ClientMessageSource so = new ClientMessageSource(messages);
Transformer gametrans = new GameTransformer(gu);
gametrans.setOutputProperty(GameTransformer.PROPERTY_OUTPUT_TYPE, "View");
try {
gametrans.transform(so, responseResult);
} catch (TransformerException e) {
throw new IOException(e);
}
}
else if(m.group(2).equals("start") || m.group(2).equals("join") || m.group(2).startsWith("event/")) {
if(!req.getMethod().equals("POST")) {
resp.setStatus(405);
resp.addHeader("Allow", "POST");
return;
}
if(u == null) {
resp.setStatus(403);
return;
}
boolean success = true;
if(m.group(2).equals("start")) {
success = g.sendStartGameRequest(u);
}
else if(m.group(2).equals("join")) {
success = g.sendPlayerJoinRequest(u);
}
else if(m.group(2).startsWith("event/")) {
String eventName = "board." + m.group(4);
Node data = doc.createElementNS(config.getGameEngineNamespace(), "data");
Node player = doc.createElementNS(config.getGameEngineNamespace(), "player");
player.appendChild(doc.createTextNode(gu.getHashedUserId()));
data.appendChild(player);
doc.appendChild(data);
DOMResult dr = new DOMResult(data);
if(req.getContentLength() > 0) {
try {
Transformer trans = config.newTransformer();
trans.transform(new StreamSource(req.getInputStream()), dr);
} catch (TransformerException e) {
// ignore error
}
}
success = g.triggerEvent(eventName, data);
}
if(!success) {
String errorMessage = "";
if(!g.isError()) {
// there was no official error, the event is simply not valid
errorMessage = "Action not valid in the current game state";
}
else {
errorMessage = g.getErrorMessage();
}
Node error = doc1.createElementNS(config.getGameEngineNamespace(), "error");
error.appendChild(doc1.createTextNode(errorMessage));
doc1.appendChild(error);
resp.setContentType("application/xml");
resp.setStatus(400);
Transformer trans;
try {
trans = config.newTransformer();
trans.transform(new DOMSource(doc1), responseResult);
} catch (TransformerConfigurationException e) {
resp.setStatus(500);
e.printStackTrace();
} catch (TransformerException e) {
resp.setStatus(500);
e.printStackTrace();
}
g.clearError();
}
else {
resp.setStatus(200);
}
}
else {
resp.setStatus(404);
resp.setContentType("text/plain");
//resp.getWriter().write("unknown url");
}
}
else {
resp.setStatus(404);
resp.getWriter().write("game not found.");
}
}
|
diff --git a/src/net/mcforge/chat/Messages.java b/src/net/mcforge/chat/Messages.java
index 011fda6..7dda7f2 100644
--- a/src/net/mcforge/chat/Messages.java
+++ b/src/net/mcforge/chat/Messages.java
@@ -1,93 +1,106 @@
/*******************************************************************************
* Copyright (c) 2012 MCForge.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
******************************************************************************/
package net.mcforge.chat;
import java.util.ArrayList;
import net.mcforge.iomodel.Player;
import net.mcforge.server.Server;
public class Messages {
protected Server server;
public Messages(Server server) { this.server = server; }
/**
* Send a message to all players on the server regardless of world
*
* @param message
*/
public void serverBroadcast(String message)
{
for (Player p : server.players)
p.sendMessage(message);
}
/**
* Send a message to all players in the specified world
*
* @param message
* @param world
*/
public void worldBroadcast(String message, String world)
{
for (Player p : server.players)
{
if(p.world == world)
p.sendMessage(message);
}
}
/**
* Send a message to a specified username
*
* @param message
* @param playerName
*/
public void sendMessage(String message, String playerName)
{
for (Player p : server.players)
if(p.username == playerName)
p.sendMessage(message);
}
public String[] split(String message) {
+ if (message.equals(""))
+ return new String[] { "" };
char[] array = message.toCharArray();
String toadd = "";
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
toadd += "" + array[i];
if (i % 64 == 0 && i != 0) {
temp.add(toadd);
toadd = "";
}
+ //If the current letter is 1 before a multiply of 64
+ //And the current index + 1 is still less than the array
+ //And the current index is a &
+ //Assume its a color code
+ //And add it to the next line
+ else if (i % 64 == 1 && i + 1 < array.length && array[i] == '&') {
+ toadd += "" + array[i + 1];
+ temp.add(toadd);
+ toadd = "";
+ i++;
+ }
}
if (!toadd.equals(""))
temp.add(toadd);
return temp.toArray(new String[temp.size()]);
}
/**
* Joins the elements of the specified array using the specified separator as a separator
* @param separator - The string to separate the joined elements of the array
* @param array - The string array to join
*/
public static String join(String[] array, String separator) {
String ret = "";
for (int i = 0; i < array.length; i++) {
ret += array[i] + separator;
}
return ret.substring(0, ret.length() - separator.length());
}
/**
* Joins the elements of the specified array using ", " as a separator
* @param array - The string array to join
*/
public static String join(String[] array) {
return join(array, ", ");
}
}
| false | true | public String[] split(String message) {
char[] array = message.toCharArray();
String toadd = "";
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
toadd += "" + array[i];
if (i % 64 == 0 && i != 0) {
temp.add(toadd);
toadd = "";
}
}
if (!toadd.equals(""))
temp.add(toadd);
return temp.toArray(new String[temp.size()]);
}
| public String[] split(String message) {
if (message.equals(""))
return new String[] { "" };
char[] array = message.toCharArray();
String toadd = "";
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < array.length; i++) {
toadd += "" + array[i];
if (i % 64 == 0 && i != 0) {
temp.add(toadd);
toadd = "";
}
//If the current letter is 1 before a multiply of 64
//And the current index + 1 is still less than the array
//And the current index is a &
//Assume its a color code
//And add it to the next line
else if (i % 64 == 1 && i + 1 < array.length && array[i] == '&') {
toadd += "" + array[i + 1];
temp.add(toadd);
toadd = "";
i++;
}
}
if (!toadd.equals(""))
temp.add(toadd);
return temp.toArray(new String[temp.size()]);
}
|
diff --git a/user/test/com/google/gwt/user/client/WindowTest.java b/user/test/com/google/gwt/user/client/WindowTest.java
index d5f44078f..3f1ceef1b 100644
--- a/user/test/com/google/gwt/user/client/WindowTest.java
+++ b/user/test/com/google/gwt/user/client/WindowTest.java
@@ -1,80 +1,80 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.client;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Test Case for {@link Cookies}.
*/
public class WindowTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.user.User";
}
public void testLocation() {
// testing reload, replace, and assign seemed to hang our junit harness. Therefore
// only testing subset of Location that is testable.
// As we have no control over these values we cannot assert much about them.
String hash = Window.Location.getHash();
String host = Window.Location.getHost();
String hostName = Window.Location.getHostName();
String href = Window.Location.getHref();
assertNull(Window.Location.getParameter("fuzzy bunny"));
String path = Window.Location.getPath();
String port = Window.Location.getPort();
String protocol = Window.Location.getProtocol();
String query = Window.Location.getQueryString();
// Check that the sum is equal to its parts.
assertEquals(host, hostName + ":" + port);
assertEquals(href, protocol + "//" + host + path + query + hash);
}
/**
* Tests the ability of the Window to get the client size correctly with and
* without visible scroll bars.
*/
- public void disabledTestGetClientSize() {
+ public void testGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
}
| true | true | public void disabledTestGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
| public void testGetClientSize() {
// Get the dimensions without any scroll bars
Window.enableScrolling(false);
final int oldClientHeight = Window.getClientHeight();
final int oldClientWidth = Window.getClientWidth();
assertTrue(oldClientHeight > 0);
assertTrue(oldClientWidth > 0);
// Compare to the dimensions with scroll bars
Window.enableScrolling(true);
final Label largeDOM = new Label();
largeDOM.setPixelSize(oldClientWidth + 100, oldClientHeight + 100);
RootPanel.get().add(largeDOM);
DeferredCommand.addCommand(new Command() {
public void execute() {
int newClientHeight = Window.getClientHeight();
int newClientWidth = Window.getClientWidth();
assertTrue(newClientHeight < oldClientHeight);
assertTrue(newClientWidth < oldClientWidth);
finishTest();
}
});
delayTestFinish(200);
}
|
diff --git a/AdminSchedulingEJB/ejbModule/com/movix/AdminScheduling/model/dao/EventDAOImpl.java b/AdminSchedulingEJB/ejbModule/com/movix/AdminScheduling/model/dao/EventDAOImpl.java
index 279d6cd..dd974e1 100644
--- a/AdminSchedulingEJB/ejbModule/com/movix/AdminScheduling/model/dao/EventDAOImpl.java
+++ b/AdminSchedulingEJB/ejbModule/com/movix/AdminScheduling/model/dao/EventDAOImpl.java
@@ -1,433 +1,439 @@
package com.movix.AdminScheduling.model.dao;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.movix.AdminScheduling.comparators.SchedulingEntryProComparator;
import com.movix.AdminScheduling.model.dto.EventDTO;
import com.movix.shared.Operador;
import com.movixla.service.scheduling.client.SchedulingClient;
import com.movixla.service.scheduling.common.SchedulingEntry;
import com.movixla.service.scheduling.common.SchedulingEntryPro;
import com.movixla.service.scheduling.common.SchedulingEntryPro.Type;
public class EventDAOImpl implements EventDAO {
private Integer eventId = 1;
private String[] daysPatterns = {"LU", "MA", "MI", "JU", "VI", "SA", "DO"};
private static final Logger logger = LoggerFactory.getLogger(EventDAOImpl.class.getName());
@Override
public void upsert(EventDTO event) {
SchedulingClient schedulingClient = SchedulingClient.getInstance();
List<SchedulingEntryPro> schedulingEntryPros = event.getEntries();
List<SchedulingEntryPro> newSchedulingEntryPros = new ArrayList<SchedulingEntryPro>();
for(int i = 0; i < daysPatterns.length; i++){
for(String key : event.getDias().keySet()){
String[] days = key.split(",");
for(int j = 0; j < days.length; j++){
if(daysPatterns[i].equals(days[j])){
String schedule = event.getDias().get(key);
String[] daysSchedule = schedule.split("\\|");
int h = 0;
for(int k = 0; k < daysSchedule.length; k++){
String[] rangesByDay = daysSchedule[k].trim().split(",");
String lastKey = "-1";
for(int l = 0; l < rangesByDay.length; l++){
SchedulingEntryPro newEntry = new SchedulingEntryPro();
String dayPattern = l == 0 && k == 0 ? daysPatterns[i] : "+" + k + "d";
String startHour = rangesByDay[l].trim().split("-")[0];
String endHour = rangesByDay[l].trim().split("-")[1];
String spForKey = event.getSp() == null ? "_" : event.getSp();
String entryKey = event.getProducto() + ":" + event.getOperador().getIdBD() + ":" + spForKey + ":_:" +
"d" + i + "-h" + h + "-" + event.getTipo();
newEntry.setActive(true);
newEntry.setDayPattern(dayPattern);
newEntry.setEndHour(endHour.trim());
newEntry.setKey(entryKey);
newEntry.setOperator(event.getOperador().getIdBD());
newEntry.setParentKey(lastKey);
newEntry.setProduct(event.getProducto());
newEntry.setServicePrice(event.getSp());
newEntry.setStartHour(startHour.trim());
newEntry.setType(Type.valueOf(event.getTipo()));
newEntry.setActive(event.isActive());
newSchedulingEntryPros.add(newEntry);
lastKey = entryKey;
h++;
}
}
}
}
}
}
System.out.println("=====NUEVO=====");
for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
System.out.println(newEntry);
}
if(schedulingEntryPros != null){
System.out.println("=====VIEJO=====");
for(SchedulingEntryPro oldEntry : schedulingEntryPros){
System.out.println(oldEntry);
}
}
- for(int i = 0; i < Math.max(newSchedulingEntryPros.size(), schedulingEntryPros.size()); i++){
- SchedulingEntryPro toSave = new SchedulingEntryPro();
- if(i < newSchedulingEntryPros.size()){
- toSave = newSchedulingEntryPros.get(i);
- if(i < schedulingEntryPros.size()){
- toSave.setId(schedulingEntryPros.get(i).getId());
+ if(schedulingEntryPros != null){
+ for(int i = 0; i < Math.max(newSchedulingEntryPros.size(), schedulingEntryPros.size()); i++){
+ SchedulingEntryPro toSave = new SchedulingEntryPro();
+ if(i < newSchedulingEntryPros.size()){
+ toSave = newSchedulingEntryPros.get(i);
+ if(i < schedulingEntryPros.size()){
+ toSave.setId(schedulingEntryPros.get(i).getId());
+ }
+ } else {
+ toSave = schedulingEntryPros.get(i);
+ toSave.setActive(false);
}
- } else {
- toSave = schedulingEntryPros.get(i);
- toSave.setActive(false);
+ schedulingClient.upsert(toSave);
+ }
+ } else {
+ for(int i = 0; i < newSchedulingEntryPros.size(); i++){
+ schedulingClient.upsert(newSchedulingEntryPros.get(i));
}
- schedulingClient.upsert(toSave);
}
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// newEntry.setId(oldEntry.getId());
// break;
// }
// }
// }
// schedulingClient.upsert(newEntry);
// }
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// boolean exists = false;
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// exists = true;
// break;
// }
// }
// if(!exists){
// oldEntry.setActive(false);
// schedulingClient.upsert(oldEntry);
// }
// }
// }
}
@Override
public List<EventDTO> findAll(){
List<EventDTO> events = new ArrayList<EventDTO>();
SchedulingClient schedulingClient = SchedulingClient.getInstance();
List<SchedulingEntryPro> schedulingEntries = schedulingClient.getEntries();
// boolean found = false;
// for(SchedulingEntryPro entry : schedulingEntries){
// String sp = entry.getServicePrice() == null ? "" : entry.getServicePrice();
// if(sp.equals("nuevo")){
// found = true;
// break;
// }
// }
// if(found) System.out.println("Encontrado nuevo");
Collections.sort(schedulingEntries, new SchedulingEntryProComparator());
SchedulingEntryPro last = new SchedulingEntryPro();
String hourSchedule = "", lastDay = "", lastServicePrice = "";
BiMap<String, String> daysMap = HashBiMap.create(7);
List<SchedulingEntryPro> eventEntries = new ArrayList<SchedulingEntryPro>();
boolean first = true;
for(SchedulingEntryPro entry : schedulingEntries){
lastServicePrice = last.getServicePrice() == null ? "" : last.getServicePrice();
if(first){
last = entry;
lastDay = entry.getDayPattern();
first = false;
}
eventEntries.add(last);
if(mustCreateEvent(last.getKey(), entry.getKey())){
putScheduleInMap(hourSchedule, lastDay, daysMap);
addNewEvent(events, last, lastServicePrice, daysMap, eventEntries);
eventEntries = new ArrayList<SchedulingEntryPro>();
lastDay = entry.getDayPattern();
hourSchedule = getSchedule(entry);
daysMap = HashBiMap.create(7);
} else {
String dayPattern = entry.getDayPattern();
if(Arrays.asList(daysPatterns).contains(dayPattern)){
if(dayPattern.equals(lastDay)){
hourSchedule += getSchedule(entry);
} else {
putScheduleInMap(hourSchedule, lastDay, daysMap);
hourSchedule = getSchedule(entry);
}
lastDay = dayPattern;
} else {
int daysOff = Integer.parseInt(dayPattern.substring(1,2));
int daysPassed = hourSchedule.length() - hourSchedule.replace("|", "").length();
String schedule = getSchedule(entry);
boolean newDay = false;
if(daysOff > daysPassed){
int daysDiff = daysOff - daysPassed;
String separator = " ";
for(int i = 0; i < daysDiff; i++){
separator += "| ";
}
schedule = separator + schedule;
newDay = true;
}
hourSchedule += ( newDay ? "" : ", " ) + schedule;
}
}
last = entry;
}
lastDay = last.getDayPattern();
putScheduleInMap(hourSchedule, lastDay, daysMap);
addNewEvent(events, last, lastServicePrice, daysMap, eventEntries);
return events;
}
// private List<SchedulingEntryPro> eventToSchedulingEntryPros(EventDTO event){
// return null;
// }
// @Override
// public List<EventDTO> findAll(){
// List<EventDTO> events = new ArrayList<EventDTO>();
// SchedulingClient schedulingClient = SchedulingClient.getInstance();
// List<SchedulingEntryPro> schedulingEntries = schedulingClient.getEntries();
// Map<String, List<SchedulingEntryPro>> groupedEntries = new HashMap<String, List<SchedulingEntryPro>>();
//
// for(SchedulingEntryPro entry : schedulingEntries){
// String eKey = entry.getServicePrice() + "|" + entry.getType();
// groupedEntries.get(eKey);
// if(groupedEntries.get(eKey) == null){
// List<SchedulingEntryPro> newList = new ArrayList<SchedulingEntryPro>();
// newList.add(entry);
// groupedEntries.put(eKey, newList);
// } else {
// groupedEntries.get(eKey).add(entry);
// }
// }
//
// for(String key : groupedEntries.keySet()){
// System.out.println("=====" + key + "=====");
// for(SchedulingEntryPro ent : groupedEntries.get(key)){
// System.out.println("\t" + ent.getKey() + "=>" + ent.getStart() + "-" + ent.getEnd());
// }
// }
//
// for(List<SchedulingEntryPro> entries : groupedEntries.values()){
// EventDTO newEvent = new EventDTO();
// BiMap<String, String> daysMap = HashBiMap.create(7);
// Operador operator = Operador.getOperadorPorIdBD(entries.get(0).getOperator());;
// String product = entries.get(0).getProduct();;
// String sp = entries.get(0).getServicePrice();
// Type type = entries.get(0).getType();
// String lastPattern = "";
// for(int i = 0; i < entries.size(); i++){
// int d = 0, h = 0;
// SchedulingEntryPro nextEntry = new SchedulingEntryPro();
// boolean found = false;
// for(SchedulingEntryPro entry : entries){
// String key = product + ":"+ operator.getIdBD() + ":" + sp + ":_:d" + d + "-h" + h + "-" + type;
// String nextDayKey = product + ":"+ operator.getIdBD() + ":" + sp + ":_:d" + d + "-h0" + "-" + type;
// String nextHourKey = product + ":"+ operator.getIdBD() + ":" + sp + ":_:d" + d + "-h" + (h + 1) + "-" + type;
// if(entry.getKey().equals(key) && !found){
// nextEntry = entry;
// found = true;
// }
// if(entry.getKey().equals(nextHourKey)){
// h++;
// } else if(entry.getKey().equals(nextDayKey)){
// d++;
// }
// }
// String range = nextEntry.getStart() + " - " + nextEntry.getEnd();
// String dayPattern = nextEntry.getDayPattern();
// System.out.println(dayPattern + " || " + (product + ":"+ operator.getIdBD() + ":" + sp + ":_:d" + d + "-h" + h + "-" + type));
//
// if(Arrays.asList(daysPatterns).contains(dayPattern)){
// daysMap.put(dayPattern, range);
// lastPattern = dayPattern;
// } else {
// String schedule = daysMap.get(lastPattern);
// int daysOff = Integer.parseInt(dayPattern.substring(1,2));
// int daysPassed = schedule.length() - schedule.replace("|", "").length();
// String separator = ", ";
// if(daysOff > daysPassed){
// int daysDiff = daysOff - daysPassed;
// separator = " ";
// for(int k = 0; k < daysDiff; k++){
// separator += "| ";
// }
// schedule = separator + range;
// }
// daysMap.put(lastPattern, separator + range);
// }
// }
// newEvent.setDias(dayMerge(daysMap));
// newEvent.setEntries(entries);
// newEvent.setId(eventId);
// newEvent.setOperador(operator);
// newEvent.setProducto(product);
// newEvent.setSp(sp);
// newEvent.setTipo(type.toString());
// }
//
// return events;
// }
private BiMap<String, String> dayMerge(BiMap<String, String> daysMap){
BiMap<String, String> ret = HashBiMap.create(7);
for(String key : daysMap.keySet()){
for(String secondKey : daysMap.keySet()){
if(daysMap.get(key).equals(daysMap.get(secondKey))){
ret.put(key + "," + secondKey, daysMap.get(key));
}
}
}
return ret;
}
private String getSchedule(SchedulingEntryPro entry) {
if(entry.getStart().equals("*") || entry.getEnd().equals("*")){
return "* - *";
}
// SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
// Date startDate = new Date();
// Date endDate = new Date();
// Operador operador = Operador.getOperadorPorIdBD(entry.getOperator());
// String start = entry.getStart(), end = entry.getEnd();
// try {
// startDate = formatter.parse(entry.getStart());
// endDate = formatter.parse(entry.getEnd());
// } catch (ParseException e) {
// e.printStackTrace();
// }
// if(operador != null){
// start = DateUtil.formatearHora(startDate, operador.getPais());
// end = DateUtil.formatearHora(endDate, operador.getPais());
// }
return entry.getStart() + " - " + entry.getEnd();
}
private void putScheduleInMap(String hourSchedule, String lastDay,
BiMap<String, String> daysMap) {
if(!daysMap.containsValue(hourSchedule)){
daysMap.put(lastDay, hourSchedule);
} else {
updateKeyAndPut(hourSchedule, lastDay, daysMap);
}
}
private void addNewEvent(List<EventDTO> events, SchedulingEntryPro last,
String lastServicePrice, BiMap<String, String> daysMap,
List<SchedulingEntryPro> eventEntries) {
EventDTO newEvent = new EventDTO();
String key = last.getProduct() + ":" + last.getOperator() + ":" + lastServicePrice + ":" + last.getKey().substring(last.getKey().lastIndexOf("-") + 1);
newEvent.setId(eventId);
newEvent.setDias(daysMap);
newEvent.setKey(key);
newEvent.setOperador(Operador.getOperadorPorIdBD(last.getOperator()));
newEvent.setProducto(last.getProduct());
newEvent.setSp(lastServicePrice);
newEvent.setTipo(last.getKey().substring(last.getKey().lastIndexOf("-") + 1));
newEvent.setEntries(eventEntries);
events.add(newEvent);
eventId++;
}
private void updateKeyAndPut(String hourSchedule, String lastDay,
BiMap<String, String> daysMap) {
String oldKey = daysMap.inverse().get(hourSchedule);
String newKey = oldKey + "," + lastDay;
daysMap.remove(oldKey);
daysMap.put(newKey, hourSchedule);
}
private BiMap<String, String> getEventShortDays(BiMap<String, String> daysMap){
BiMap<String, String> auxMap = HashBiMap.create(7);;
for(String key : daysMap.keySet()){
String shortKey = getShortDays(key);
auxMap.put(shortKey, daysMap.get(key));
}
return auxMap;
}
private String getShortDays(String days){
if(days.length() == 0){
return "";
}
String shortDays = "";
int i = 0, initial = -1;
String[] daysTokens = days.split(",");
for(i = 0; i < daysPatterns.length; i++){
boolean exists = false;
for(int j = 0; j < daysTokens.length; j++){
if(daysTokens[j].equals(daysPatterns[i])){
exists = true;
break;
}
}
if(exists && initial == -1){
initial = i;
}
if(initial >= 0 && !exists){
shortDays = concatShortDays(shortDays, i, initial);
initial = -1;
}
}
if(initial >= 0){
shortDays = concatShortDays(shortDays, i, initial);
}
return shortDays.substring(0, shortDays.length() - 2);
}
private String concatShortDays(String shortDays, int i, int initial) {
if(i - initial == 1){
shortDays += daysPatterns[i - 1];
} else if(i - initial == 2){
shortDays += daysPatterns[i - 2] + "," + daysPatterns[i - 1];
} else {
shortDays += daysPatterns[initial] + " a " + daysPatterns[i - 1];
}
shortDays += ", ";
return shortDays;
}
private boolean mustCreateEvent(String lastKey, String entryKey){
boolean different = false;
String[] lastKeyTokens = lastKey.split(":");
String[] entryKeyTokens = entryKey.split(":");
for(int i = 0; i < lastKeyTokens.length; i++){
if(i == lastKeyTokens.length - 1){
lastKeyTokens[i] = lastKeyTokens[i].replaceAll("[0-9]","");
entryKeyTokens[i] = entryKeyTokens[i].replaceAll("[0-9]","");
}
if(!lastKeyTokens[i].equals(entryKeyTokens[i])){
different = true;
}
}
return different;
}
public enum Product {
MP, SUS
}
public void test(){
SchedulingClient schedulingClient = SchedulingClient.getInstance();
List<SchedulingEntryPro> schedulingEntries = schedulingClient.getEntries();
for(SchedulingEntryPro entry : schedulingEntries){
entry.setActive(true);
schedulingClient.upsert(entry);
}
}
}
| false | true | public void upsert(EventDTO event) {
SchedulingClient schedulingClient = SchedulingClient.getInstance();
List<SchedulingEntryPro> schedulingEntryPros = event.getEntries();
List<SchedulingEntryPro> newSchedulingEntryPros = new ArrayList<SchedulingEntryPro>();
for(int i = 0; i < daysPatterns.length; i++){
for(String key : event.getDias().keySet()){
String[] days = key.split(",");
for(int j = 0; j < days.length; j++){
if(daysPatterns[i].equals(days[j])){
String schedule = event.getDias().get(key);
String[] daysSchedule = schedule.split("\\|");
int h = 0;
for(int k = 0; k < daysSchedule.length; k++){
String[] rangesByDay = daysSchedule[k].trim().split(",");
String lastKey = "-1";
for(int l = 0; l < rangesByDay.length; l++){
SchedulingEntryPro newEntry = new SchedulingEntryPro();
String dayPattern = l == 0 && k == 0 ? daysPatterns[i] : "+" + k + "d";
String startHour = rangesByDay[l].trim().split("-")[0];
String endHour = rangesByDay[l].trim().split("-")[1];
String spForKey = event.getSp() == null ? "_" : event.getSp();
String entryKey = event.getProducto() + ":" + event.getOperador().getIdBD() + ":" + spForKey + ":_:" +
"d" + i + "-h" + h + "-" + event.getTipo();
newEntry.setActive(true);
newEntry.setDayPattern(dayPattern);
newEntry.setEndHour(endHour.trim());
newEntry.setKey(entryKey);
newEntry.setOperator(event.getOperador().getIdBD());
newEntry.setParentKey(lastKey);
newEntry.setProduct(event.getProducto());
newEntry.setServicePrice(event.getSp());
newEntry.setStartHour(startHour.trim());
newEntry.setType(Type.valueOf(event.getTipo()));
newEntry.setActive(event.isActive());
newSchedulingEntryPros.add(newEntry);
lastKey = entryKey;
h++;
}
}
}
}
}
}
System.out.println("=====NUEVO=====");
for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
System.out.println(newEntry);
}
if(schedulingEntryPros != null){
System.out.println("=====VIEJO=====");
for(SchedulingEntryPro oldEntry : schedulingEntryPros){
System.out.println(oldEntry);
}
}
for(int i = 0; i < Math.max(newSchedulingEntryPros.size(), schedulingEntryPros.size()); i++){
SchedulingEntryPro toSave = new SchedulingEntryPro();
if(i < newSchedulingEntryPros.size()){
toSave = newSchedulingEntryPros.get(i);
if(i < schedulingEntryPros.size()){
toSave.setId(schedulingEntryPros.get(i).getId());
}
} else {
toSave = schedulingEntryPros.get(i);
toSave.setActive(false);
}
schedulingClient.upsert(toSave);
}
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// newEntry.setId(oldEntry.getId());
// break;
// }
// }
// }
// schedulingClient.upsert(newEntry);
// }
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// boolean exists = false;
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// exists = true;
// break;
// }
// }
// if(!exists){
// oldEntry.setActive(false);
// schedulingClient.upsert(oldEntry);
// }
// }
// }
}
| public void upsert(EventDTO event) {
SchedulingClient schedulingClient = SchedulingClient.getInstance();
List<SchedulingEntryPro> schedulingEntryPros = event.getEntries();
List<SchedulingEntryPro> newSchedulingEntryPros = new ArrayList<SchedulingEntryPro>();
for(int i = 0; i < daysPatterns.length; i++){
for(String key : event.getDias().keySet()){
String[] days = key.split(",");
for(int j = 0; j < days.length; j++){
if(daysPatterns[i].equals(days[j])){
String schedule = event.getDias().get(key);
String[] daysSchedule = schedule.split("\\|");
int h = 0;
for(int k = 0; k < daysSchedule.length; k++){
String[] rangesByDay = daysSchedule[k].trim().split(",");
String lastKey = "-1";
for(int l = 0; l < rangesByDay.length; l++){
SchedulingEntryPro newEntry = new SchedulingEntryPro();
String dayPattern = l == 0 && k == 0 ? daysPatterns[i] : "+" + k + "d";
String startHour = rangesByDay[l].trim().split("-")[0];
String endHour = rangesByDay[l].trim().split("-")[1];
String spForKey = event.getSp() == null ? "_" : event.getSp();
String entryKey = event.getProducto() + ":" + event.getOperador().getIdBD() + ":" + spForKey + ":_:" +
"d" + i + "-h" + h + "-" + event.getTipo();
newEntry.setActive(true);
newEntry.setDayPattern(dayPattern);
newEntry.setEndHour(endHour.trim());
newEntry.setKey(entryKey);
newEntry.setOperator(event.getOperador().getIdBD());
newEntry.setParentKey(lastKey);
newEntry.setProduct(event.getProducto());
newEntry.setServicePrice(event.getSp());
newEntry.setStartHour(startHour.trim());
newEntry.setType(Type.valueOf(event.getTipo()));
newEntry.setActive(event.isActive());
newSchedulingEntryPros.add(newEntry);
lastKey = entryKey;
h++;
}
}
}
}
}
}
System.out.println("=====NUEVO=====");
for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
System.out.println(newEntry);
}
if(schedulingEntryPros != null){
System.out.println("=====VIEJO=====");
for(SchedulingEntryPro oldEntry : schedulingEntryPros){
System.out.println(oldEntry);
}
}
if(schedulingEntryPros != null){
for(int i = 0; i < Math.max(newSchedulingEntryPros.size(), schedulingEntryPros.size()); i++){
SchedulingEntryPro toSave = new SchedulingEntryPro();
if(i < newSchedulingEntryPros.size()){
toSave = newSchedulingEntryPros.get(i);
if(i < schedulingEntryPros.size()){
toSave.setId(schedulingEntryPros.get(i).getId());
}
} else {
toSave = schedulingEntryPros.get(i);
toSave.setActive(false);
}
schedulingClient.upsert(toSave);
}
} else {
for(int i = 0; i < newSchedulingEntryPros.size(); i++){
schedulingClient.upsert(newSchedulingEntryPros.get(i));
}
}
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// newEntry.setId(oldEntry.getId());
// break;
// }
// }
// }
// schedulingClient.upsert(newEntry);
// }
// if(schedulingEntryPros != null){
// for(SchedulingEntryPro oldEntry : schedulingEntryPros){
// boolean exists = false;
// for(SchedulingEntryPro newEntry : newSchedulingEntryPros){
// if(newEntry.getKey().equals(oldEntry.getKey())){
// exists = true;
// break;
// }
// }
// if(!exists){
// oldEntry.setActive(false);
// schedulingClient.upsert(oldEntry);
// }
// }
// }
}
|
diff --git a/src/org/apache/xerces/impl/dtd/XMLDTDProcessor.java b/src/org/apache/xerces/impl/dtd/XMLDTDProcessor.java
index 1ec5e179..3838bd8c 100644
--- a/src/org/apache/xerces/impl/dtd/XMLDTDProcessor.java
+++ b/src/org/apache/xerces/impl/dtd/XMLDTDProcessor.java
@@ -1,1657 +1,1657 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.impl.dtd;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.msg.XMLMessageFormatter;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.XMLSymbols;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.XMLDTDContentModelHandler;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.grammars.Grammar;
import org.apache.xerces.xni.grammars.XMLGrammarDescription;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.parser.XMLComponent;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDTDContentModelFilter;
import org.apache.xerces.xni.parser.XMLDTDContentModelSource;
import org.apache.xerces.xni.parser.XMLDTDFilter;
import org.apache.xerces.xni.parser.XMLDTDSource;
/**
* The DTD processor. The processor implements a DTD
* filter: receiving DTD events from the DTD scanner; validating
* the content and structure; building a grammar, if applicable;
* and notifying the DTDHandler of the information resulting from the
* process.
* <p>
* This component requires the following features and properties from the
* component manager that uses it:
* <ul>
* <li>http://xml.org/sax/features/namespaces</li>
* <li>http://apache.org/xml/properties/internal/symbol-table</li>
* <li>http://apache.org/xml/properties/internal/error-reporter</li>
* <li>http://apache.org/xml/properties/internal/grammar-pool</li>
* <li>http://apache.org/xml/properties/internal/datatype-validator-factory</li>
* </ul>
*
* @author Neil Graham, IBM
*
* @version $Id$
*/
public class XMLDTDProcessor
implements XMLComponent, XMLDTDFilter, XMLDTDContentModelFilter {
//
// Constants
//
/** Top level scope (-1). */
private static final int TOP_LEVEL_SCOPE = -1;
// feature identifiers
/** Feature identifier: validation. */
protected static final String VALIDATION =
Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;
/** Feature identifier: notify character references. */
protected static final String NOTIFY_CHAR_REFS =
Constants.XERCES_FEATURE_PREFIX + Constants.NOTIFY_CHAR_REFS_FEATURE;
/** Feature identifier: warn on duplicate attdef */
protected static final String WARN_ON_DUPLICATE_ATTDEF =
Constants.XERCES_FEATURE_PREFIX +Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE;
// property identifiers
/** Property identifier: symbol table. */
protected static final String SYMBOL_TABLE =
Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY;
/** Property identifier: error reporter. */
protected static final String ERROR_REPORTER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;
/** Property identifier: grammar pool. */
protected static final String GRAMMAR_POOL =
Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;
/** Property identifier: validator . */
protected static final String DTD_VALIDATOR =
Constants.XERCES_PROPERTY_PREFIX + Constants.DTD_VALIDATOR_PROPERTY;
// recognized features and properties
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
VALIDATION,
WARN_ON_DUPLICATE_ATTDEF,
NOTIFY_CHAR_REFS,
};
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = {
null,
Boolean.FALSE,
null,
};
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
SYMBOL_TABLE,
ERROR_REPORTER,
GRAMMAR_POOL,
DTD_VALIDATOR,
};
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = {
null,
null,
null,
null,
};
// debugging
//
// Data
//
// features
/** Validation. */
protected boolean fValidation;
/** Validation against only DTD */
protected boolean fDTDValidation;
/** warn on duplicate attribute definition, this feature works only when validation is true */
protected boolean fWarnDuplicateAttdef;
// properties
/** Symbol table. */
protected SymbolTable fSymbolTable;
/** Error reporter. */
protected XMLErrorReporter fErrorReporter;
/** Grammar bucket. */
protected DTDGrammarBucket fGrammarBucket;
// the validator to which we look for our grammar bucket (the
// validator needs to hold the bucket so that it can initialize
// the grammar with details like whether it's for a standalone document...
protected XMLDTDValidator fValidator;
// the grammar pool we'll try to add the grammar to:
protected XMLGrammarPool fGrammarPool;
// what's our Locale?
protected Locale fLocale;
// handlers
/** DTD handler. */
protected XMLDTDHandler fDTDHandler;
/** DTD source. */
protected XMLDTDSource fDTDSource;
/** DTD content model handler. */
protected XMLDTDContentModelHandler fDTDContentModelHandler;
/** DTD content model source. */
protected XMLDTDContentModelSource fDTDContentModelSource;
// grammars
/** DTD Grammar. */
protected DTDGrammar fDTDGrammar;
// state
/** Perform validation. */
private boolean fPerformValidation;
/** True if in an ignore conditional section of the DTD. */
protected boolean fInDTDIgnore;
// information regarding the current element
// validation states
/** Mixed. */
private boolean fMixed;
// temporary variables
/** Temporary entity declaration. */
private XMLEntityDecl fEntityDecl = new XMLEntityDecl();
/** Notation declaration hash. */
private Hashtable fNDataDeclNotations = new Hashtable();
/** DTD element declaration name. */
private String fDTDElementDeclName = null;
/** Mixed element type "hash". */
private Vector fMixedElementTypes = new Vector();
/** Element declarations in DTD. */
private Vector fDTDElementDecls = new Vector();
// to check for duplicate ID or ANNOTATION attribute declare in
// ATTLIST, and misc VCs
/** ID attribute names. */
private Hashtable fTableOfIDAttributeNames;
/** NOTATION attribute names. */
private Hashtable fTableOfNOTATIONAttributeNames;
/** NOTATION enumeration values. */
private Hashtable fNotationEnumVals;
//
// Constructors
//
/** Default constructor. */
public XMLDTDProcessor() {
// initialize data
} // <init>()
//
// XMLComponent methods
//
/*
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws SAXException Thrown by component on finitialization error.
* For example, if a feature or property is
* required for the operation of the component, the
* component manager may throw a
* SAXNotRecognizedException or a
* SAXNotSupportedException.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
// sax features
try {
fValidation = componentManager.getFeature(VALIDATION);
}
catch (XMLConfigurationException e) {
fValidation = false;
}
try {
fDTDValidation = !(componentManager.getFeature(Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE));
}
catch (XMLConfigurationException e) {
// must be in a schema-less configuration!
fDTDValidation = true;
}
// Xerces features
try {
fWarnDuplicateAttdef = componentManager.getFeature(WARN_ON_DUPLICATE_ATTDEF);
}
catch (XMLConfigurationException e) {
fWarnDuplicateAttdef = false;
}
// get needed components
fErrorReporter = (XMLErrorReporter)componentManager.getProperty(Constants.XERCES_PROPERTY_PREFIX+Constants.ERROR_REPORTER_PROPERTY);
fSymbolTable = (SymbolTable)componentManager.getProperty(Constants.XERCES_PROPERTY_PREFIX+Constants.SYMBOL_TABLE_PROPERTY);
try {
fGrammarPool= (XMLGrammarPool)componentManager.getProperty(GRAMMAR_POOL);
} catch (XMLConfigurationException e) {
fGrammarPool = null;
}
try {
fValidator = (XMLDTDValidator)componentManager.getProperty(DTD_VALIDATOR);
} catch (XMLConfigurationException e) {
fValidator = null;
} catch (ClassCastException e) {
fValidator = null;
}
// we get our grammarBucket from the validator...
if(fValidator != null) {
fGrammarBucket = fValidator.getGrammarBucket();
} else {
fGrammarBucket = null;
}
reset();
} // reset(XMLComponentManager)
protected void reset() {
// clear grammars
fDTDGrammar = null;
// initialize state
fInDTDIgnore = false;
fNDataDeclNotations.clear();
init();
}
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return (String[])(RECOGNIZED_FEATURES.clone());
} // getRecognizedFeatures():String[]
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
} // setFeature(String,boolean)
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return (String[])(RECOGNIZED_PROPERTIES.clone());
} // getRecognizedProperties():String[]
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws SAXNotRecognizedException The component should not throw
* this exception.
* @throws SAXNotSupportedException The component should not throw
* this exception.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
} // setProperty(String,Object)
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*
* @param featureId The feature identifier.
*
* @since Xerces 2.2.0
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*
* @param propertyId The property identifier.
*
* @since Xerces 2.2.0
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
//
// XMLDTDSource methods
//
/**
* Sets the DTD handler.
*
* @param dtdHandler The DTD handler.
*/
public void setDTDHandler(XMLDTDHandler dtdHandler) {
fDTDHandler = dtdHandler;
} // setDTDHandler(XMLDTDHandler)
/**
* Returns the DTD handler.
*
* @return The DTD handler.
*/
public XMLDTDHandler getDTDHandler() {
return fDTDHandler;
} // getDTDHandler(): XMLDTDHandler
//
// XMLDTDContentModelSource methods
//
/**
* Sets the DTD content model handler.
*
* @param dtdContentModelHandler The DTD content model handler.
*/
public void setDTDContentModelHandler(XMLDTDContentModelHandler dtdContentModelHandler) {
fDTDContentModelHandler = dtdContentModelHandler;
} // setDTDContentModelHandler(XMLDTDContentModelHandler)
/**
* Gets the DTD content model handler.
*
* @return dtdContentModelHandler The DTD content model handler.
*/
public XMLDTDContentModelHandler getDTDContentModelHandler() {
return fDTDContentModelHandler;
} // getDTDContentModelHandler(): XMLDTDContentModelHandler
//
// XMLDTDContentModelHandler and XMLDTDHandler methods
//
/**
* The start of the DTD external subset.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startExternalSubset(XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
if(fDTDGrammar != null)
fDTDGrammar.startExternalSubset(identifier, augs);
if(fDTDHandler != null){
fDTDHandler.startExternalSubset(identifier, augs);
}
}
/**
* The end of the DTD external subset.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endExternalSubset(Augmentations augs) throws XNIException {
if(fDTDGrammar != null)
fDTDGrammar.endExternalSubset(augs);
if(fDTDHandler != null){
fDTDHandler.endExternalSubset(augs);
}
}
/**
* Check standalone entity reference.
* Made static to make common between the validator and loader.
*
* @param name
*@param grammar grammar to which entity belongs
* @param tempEntityDecl empty entity declaration to put results in
* @param errorReporter error reporter to send errors to
*
* @throws XNIException Thrown by application to signal an error.
*/
protected static void checkStandaloneEntityRef(String name, DTDGrammar grammar,
XMLEntityDecl tempEntityDecl, XMLErrorReporter errorReporter) throws XNIException {
// check VC: Standalone Document Declartion, entities references appear in the document.
int entIndex = grammar.getEntityDeclIndex(name);
if (entIndex > -1) {
grammar.getEntityDecl(entIndex, tempEntityDecl);
if (tempEntityDecl.inExternal) {
errorReporter.reportError( XMLMessageFormatter.XML_DOMAIN,
"MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE",
new Object[]{name}, XMLErrorReporter.SEVERITY_ERROR);
}
}
}
/**
* A comment.
*
* @param text The text in the comment.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by application to signal an error.
*/
public void comment(XMLString text, Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.comment(text, augs);
if (fDTDHandler != null) {
fDTDHandler.comment(text, augs);
}
} // comment(XMLString)
/**
* A processing instruction. Processing instructions consist of a
* target name and, optionally, text data. The data is only meaningful
* to the application.
* <p>
* Typically, a processing instruction's data will contain a series
* of pseudo-attributes. These pseudo-attributes follow the form of
* element attributes but are <strong>not</strong> parsed or presented
* to the application as anything other than text. The application is
* responsible for parsing the data.
*
* @param target The target.
* @param data The data or null if none specified.
* @param augs Additional information that may include infoset augmentations
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.processingInstruction(target, data, augs);
if (fDTDHandler != null) {
fDTDHandler.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString)
//
// XMLDTDHandler methods
//
/**
* The start of the DTD.
*
* @param locator The document locator, or null if the document
* location cannot be reported during the parsing of
* the document DTD. However, it is <em>strongly</em>
* recommended that a locator be supplied that can
* at least report the base system identifier of the
* DTD.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startDTD(XMLLocator locator, Augmentations augs) throws XNIException {
// initialize state
fNDataDeclNotations.clear();
fDTDElementDecls.removeAllElements();
// the grammar bucket's DTDGrammar will now be the
// one we want, whether we're constructing it or not.
// if we're not constructing it, then we should not have a reference
// to it!
if( !fGrammarBucket.getActiveGrammar().isImmutable()) {
fDTDGrammar = fGrammarBucket.getActiveGrammar();
}
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.startDTD(locator, augs);
if (fDTDHandler != null) {
fDTDHandler.startDTD(locator, augs);
}
} // startDTD(XMLLocator)
/**
* Characters within an IGNORE conditional section.
*
* @param text The ignored text.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void ignoredCharacters(XMLString text, Augmentations augs) throws XNIException {
// ignored characters in DTD
if(fDTDGrammar != null )
fDTDGrammar.ignoredCharacters(text, augs);
if (fDTDHandler != null) {
fDTDHandler.ignoredCharacters(text, augs);
}
}
/**
* Notifies of the presence of a TextDecl line in an entity. If present,
* this method will be called immediately following the startParameterEntity call.
* <p>
* <strong>Note:</strong> This method is only called for external
* parameter entities referenced in the DTD.
*
* @param version The XML version, or null if not specified.
* @param encoding The IANA encoding name of the entity.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void textDecl(String version, String encoding, Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.textDecl(version, encoding, augs);
if (fDTDHandler != null) {
fDTDHandler.textDecl(version, encoding, augs);
}
}
/**
* This method notifies of the start of a parameter entity. The parameter
* entity name start with a '%' character.
*
* @param name The name of the parameter entity.
* @param identifier The resource identifier.
* @param encoding The auto-detected IANA encoding name of the entity
* stream. This value will be null in those situations
* where the entity encoding is not auto-detected (e.g.
* internal parameter entities).
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startParameterEntity(String name,
XMLResourceIdentifier identifier,
String encoding,
Augmentations augs) throws XNIException {
if (fPerformValidation && fDTDGrammar != null &&
fGrammarBucket.getStandalone()) {
checkStandaloneEntityRef(name, fDTDGrammar, fEntityDecl, fErrorReporter);
}
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.startParameterEntity(name, identifier, encoding, augs);
if (fDTDHandler != null) {
fDTDHandler.startParameterEntity(name, identifier, encoding, augs);
}
}
/**
* This method notifies the end of a parameter entity. Parameter entity
* names begin with a '%' character.
*
* @param name The name of the parameter entity.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endParameterEntity(String name, Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.endParameterEntity(name, augs);
if (fDTDHandler != null) {
fDTDHandler.endParameterEntity(name, augs);
}
}
/**
* An element declaration.
*
* @param name The name of the element.
* @param contentModel The element content model.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void elementDecl(String name, String contentModel, Augmentations augs)
throws XNIException {
//check VC: Unique Element Declaration
if (fValidation) {
if (fDTDElementDecls.contains(name)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_ELEMENT_ALREADY_DECLARED",
new Object[]{ name},
XMLErrorReporter.SEVERITY_ERROR);
}
else {
fDTDElementDecls.addElement(name);
}
}
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.elementDecl(name, contentModel, augs);
if (fDTDHandler != null) {
fDTDHandler.elementDecl(name, contentModel, augs);
}
} // elementDecl(String,String)
/**
* The start of an attribute list.
*
* @param elementName The name of the element that this attribute
* list is associated with.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startAttlist(String elementName, Augmentations augs)
throws XNIException {
// call handlers
if(fDTDGrammar != null )
fDTDGrammar.startAttlist(elementName, augs);
if (fDTDHandler != null) {
fDTDHandler.startAttlist(elementName, augs);
}
} // startAttlist(String)
/**
* An attribute declaration.
*
* @param elementName The name of the element that this attribute
* is associated with.
* @param attributeName The name of the attribute.
* @param type The attribute type. This value will be one of
* the following: "CDATA", "ENTITY", "ENTITIES",
* "ENUMERATION", "ID", "IDREF", "IDREFS",
* "NMTOKEN", "NMTOKENS", or "NOTATION".
* @param enumeration If the type has the value "ENUMERATION" or
* "NOTATION", this array holds the allowed attribute
* values; otherwise, this array is null.
* @param defaultType The attribute default type. This value will be
* one of the following: "#FIXED", "#IMPLIED",
* "#REQUIRED", or null.
* @param defaultValue The attribute default value, or null if no
* default value is specified.
* @param nonNormalizedDefaultValue The attribute default value with no normalization
* performed, or null if no default value is specified.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void attributeDecl(String elementName, String attributeName,
String type, String[] enumeration,
String defaultType, XMLString defaultValue,
XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException {
if (type != XMLSymbols.fCDATASymbol && defaultValue != null) {
normalizeDefaultAttrValue(defaultValue);
}
if (fValidation) {
boolean duplicateAttributeDef = false ;
//Get Grammar index to grammar array
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar:fGrammarBucket.getActiveGrammar());
int elementIndex = grammar.getElementDeclIndex( elementName);
if (grammar.getAttributeDeclIndex(elementIndex, attributeName) != -1) {
//more than one attribute definition is provided for the same attribute of a given element type.
duplicateAttributeDef = true ;
//this feature works only when validation is true.
if(fWarnDuplicateAttdef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ATTRIBUTE_DEFINITION",
new Object[]{ elementName, attributeName },
XMLErrorReporter.SEVERITY_WARNING );
}
}
//
// a) VC: One ID per Element Type, If duplicate ID attribute
// b) VC: ID attribute Default. if there is a declareared attribute
// default for ID it should be of type #IMPLIED or #REQUIRED
if (type == XMLSymbols.fIDSymbol) {
if (defaultValue != null && defaultValue.length != 0) {
if (defaultType == null ||
!(defaultType == XMLSymbols.fIMPLIEDSymbol ||
defaultType == XMLSymbols.fREQUIREDSymbol)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"IDDefaultTypeInvalid",
new Object[]{ attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
if (!fTableOfIDAttributeNames.containsKey(elementName)) {
fTableOfIDAttributeNames.put(elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true,
// one typical case where this could be a problem, when any XML file
// provide the ID type information through internal subset so that it is available to the parser which read
//only internal subset. Now that attribute declaration(ID Type) can again be part of external parsed entity
//referenced. At that time if parser doesn't make this distinction it will throw an error for VC One ID per
//Element Type, which (second defintion) actually should be ignored. Application behavior may differ on the
//basis of error or warning thrown. - nb.
if(!duplicateAttributeDef){
String previousIDAttributeName = (String)fTableOfIDAttributeNames.get( elementName );//rule a)
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_ID_ATTRIBUTE",
new Object[]{ elementName, previousIDAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
//
// VC: One Notaion Per Element Type, should check if there is a
// duplicate NOTATION attribute
if (type == XMLSymbols.fNOTATIONSymbol) {
// VC: Notation Attributes: all notation names in the
// (attribute) declaration must be declared.
for (int i=0; i<enumeration.length; i++) {
fNotationEnumVals.put(enumeration[i], attributeName);
}
if (fTableOfNOTATIONAttributeNames.containsKey( elementName ) == false) {
fTableOfNOTATIONAttributeNames.put( elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true, Application behavior may differ on the basis of error or
//warning thrown. - nb.
if(!duplicateAttributeDef){
String previousNOTATIONAttributeName = (String) fTableOfNOTATIONAttributeNames.get( elementName );
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE",
new Object[]{ elementName, previousNOTATIONAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// VC: No Duplicate Tokens
// XML 1.0 SE Errata - E2
if (type == XMLSymbols.fENUMERATIONSymbol || type == XMLSymbols.fNOTATIONSymbol) {
outer:
for (int i = 0; i < enumeration.length; ++i) {
for (int j = i + 1; j < enumeration.length; ++j) {
if (enumeration[i].equals(enumeration[j])) {
// Only report the first uniqueness violation. There could be others,
// but additional overhead would be incurred tracking unique tokens
// that have already been encountered. -- mrglavas
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
type == XMLSymbols.fENUMERATIONSymbol
? "MSG_DISTINCT_TOKENS_IN_ENUMERATION"
: "MSG_DISTINCT_NOTATION_IN_ENUMERATION",
new Object[]{ elementName, enumeration[i], attributeName },
XMLErrorReporter.SEVERITY_ERROR);
break outer;
}
}
}
}
// VC: Attribute Default Legal
boolean ok = true;
if (defaultValue != null &&
(defaultType == null ||
(defaultType != null && defaultType == XMLSymbols.fFIXEDSymbol))) {
String value = defaultValue.toString();
if (type == XMLSymbols.fNMTOKENSSymbol ||
type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
- StringTokenizer tokenizer = new StringTokenizer(value);
+ StringTokenizer tokenizer = new StringTokenizer(value," ");
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (type == XMLSymbols.fNMTOKENSSymbol) {
if (!isValidNmtoken(nmtoken)) {
ok = false;
break;
}
}
else if (type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
if (!isValidName(nmtoken)) {
ok = false;
break;
}
}
if (!tokenizer.hasMoreTokens()) {
break;
}
}
}
}
else {
if (type == XMLSymbols.fENTITYSymbol ||
type == XMLSymbols.fIDSymbol ||
type == XMLSymbols.fIDREFSymbol ||
type == XMLSymbols.fNOTATIONSymbol) {
if (!isValidName(value)) {
ok = false;
}
}
else if (type == XMLSymbols.fNMTOKENSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
if (!isValidNmtoken(value)) {
ok = false;
}
}
if (type == XMLSymbols.fNOTATIONSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
ok = false;
for (int i=0; i<enumeration.length; i++) {
if (defaultValue.equals(enumeration[i])) {
ok = true;
}
}
}
}
if (!ok) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_ATT_DEFAULT_INVALID",
new Object[]{attributeName, value},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
if (fDTDHandler != null) {
fDTDHandler.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
}
} // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations)
/**
* The end of an attribute list.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endAttlist(Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.endAttlist(augs);
if (fDTDHandler != null) {
fDTDHandler.endAttlist(augs);
}
} // endAttlist()
/**
* An internal entity declaration.
*
* @param name The name of the entity. Parameter entity names start with
* '%', whereas the name of a general entity is just the
* entity name.
* @param text The value of the entity.
* @param nonNormalizedText The non-normalized value of the entity. This
* value contains the same sequence of characters that was in
* the internal entity declaration, without any entity
* references expanded.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void internalEntityDecl(String name, XMLString text,
XMLString nonNormalizedText,
Augmentations augs) throws XNIException {
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar: fGrammarBucket.getActiveGrammar());
int index = grammar.getEntityDeclIndex(name) ;
//If the same entity is declared more than once, the first declaration
//encountered is binding, SAX requires only effective(first) declaration
//to be reported to the application
//REVISIT: Does it make sense to pass duplicate Entity information across
//the pipeline -- nb?
//its a new entity and hasn't been declared.
if(index == -1){
//store internal entity declaration in grammar
if(fDTDGrammar != null)
fDTDGrammar.internalEntityDecl(name, text, nonNormalizedText, augs);
// call handlers
if (fDTDHandler != null) {
fDTDHandler.internalEntityDecl(name, text, nonNormalizedText, augs);
}
}
} // internalEntityDecl(String,XMLString,XMLString)
/**
* An external entity declaration.
*
* @param name The name of the entity. Parameter entity names start
* with '%', whereas the name of a general entity is just
* the entity name.
* @param identifier An object containing all location information
* pertinent to this external entity.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void externalEntityDecl(String name, XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar: fGrammarBucket.getActiveGrammar());
int index = grammar.getEntityDeclIndex(name) ;
//If the same entity is declared more than once, the first declaration
//encountered is binding, SAX requires only effective(first) declaration
//to be reported to the application
//REVISIT: Does it make sense to pass duplicate entity information across
//the pipeline -- nb?
//its a new entity and hasn't been declared.
if(index == -1){
//store external entity declaration in grammar
if(fDTDGrammar != null)
fDTDGrammar.externalEntityDecl(name, identifier, augs);
// call handlers
if (fDTDHandler != null) {
fDTDHandler.externalEntityDecl(name, identifier, augs);
}
}
} // externalEntityDecl(String,XMLResourceIdentifier, Augmentations)
/**
* An unparsed entity declaration.
*
* @param name The name of the entity.
* @param identifier An object containing all location information
* pertinent to this entity.
* @param notation The name of the notation.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void unparsedEntityDecl(String name, XMLResourceIdentifier identifier,
String notation,
Augmentations augs) throws XNIException {
// VC: Notation declared, in the production of NDataDecl
if (fValidation) {
fNDataDeclNotations.put(name, notation);
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.unparsedEntityDecl(name, identifier, notation, augs);
if (fDTDHandler != null) {
fDTDHandler.unparsedEntityDecl(name, identifier, notation, augs);
}
} // unparsedEntityDecl(String,XMLResourceIdentifier,String,Augmentations)
/**
* A notation declaration
*
* @param name The name of the notation.
* @param identifier An object containing all location information
* pertinent to this notation.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void notationDecl(String name, XMLResourceIdentifier identifier,
Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.notationDecl(name, identifier, augs);
if (fDTDHandler != null) {
fDTDHandler.notationDecl(name, identifier, augs);
}
} // notationDecl(String,XMLResourceIdentifier, Augmentations)
/**
* The start of a conditional section.
*
* @param type The type of the conditional section. This value will
* either be CONDITIONAL_INCLUDE or CONDITIONAL_IGNORE.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #CONDITIONAL_INCLUDE
* @see #CONDITIONAL_IGNORE
*/
public void startConditional(short type, Augmentations augs) throws XNIException {
// set state
fInDTDIgnore = type == XMLDTDHandler.CONDITIONAL_IGNORE;
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.startConditional(type, augs);
if (fDTDHandler != null) {
fDTDHandler.startConditional(type, augs);
}
} // startConditional(short)
/**
* The end of a conditional section.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endConditional(Augmentations augs) throws XNIException {
// set state
fInDTDIgnore = false;
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.endConditional(augs);
if (fDTDHandler != null) {
fDTDHandler.endConditional(augs);
}
} // endConditional()
/**
* The end of the DTD.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endDTD(Augmentations augs) throws XNIException {
// save grammar
if(fDTDGrammar != null) {
fDTDGrammar.endDTD(augs);
if(fGrammarPool != null)
fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_DTD, new Grammar[] {fDTDGrammar});
}
// check VC: Notation declared, in the production of NDataDecl
if (fValidation) {
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar: fGrammarBucket.getActiveGrammar());
// VC : Notation Declared. for external entity declaration [Production 76].
Enumeration entities = fNDataDeclNotations.keys();
while (entities.hasMoreElements()) {
String entity = (String) entities.nextElement();
String notation = (String) fNDataDeclNotations.get(entity);
if (grammar.getNotationDeclIndex(notation) == -1) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_NOTATION_NOT_DECLARED_FOR_UNPARSED_ENTITYDECL",
new Object[]{entity, notation},
XMLErrorReporter.SEVERITY_ERROR);
}
}
// VC: Notation Attributes:
// all notation names in the (attribute) declaration must be declared.
Enumeration notationVals = fNotationEnumVals.keys();
while (notationVals.hasMoreElements()) {
String notation = (String) notationVals.nextElement();
String attributeName = (String) fNotationEnumVals.get(notation);
if (grammar.getNotationDeclIndex(notation) == -1) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE",
new Object[]{attributeName, notation},
XMLErrorReporter.SEVERITY_ERROR);
}
}
fTableOfIDAttributeNames = null;//should be safe to release these references
fTableOfNOTATIONAttributeNames = null;
}
// call handlers
if (fDTDHandler != null) {
fDTDHandler.endDTD(augs);
}
} // endDTD()
// sets the XMLDTDSource of this handler
public void setDTDSource(XMLDTDSource source ) {
fDTDSource = source;
} // setDTDSource(XMLDTDSource)
// returns the XMLDTDSource of this handler
public XMLDTDSource getDTDSource() {
return fDTDSource;
} // getDTDSource(): XMLDTDSource
//
// XMLDTDContentModelHandler methods
//
// sets the XMLContentModelDTDSource of this handler
public void setDTDContentModelSource(XMLDTDContentModelSource source ) {
fDTDContentModelSource = source;
} // setDTDContentModelSource(XMLDTDContentModelSource)
// returns the XMLDTDSource of this handler
public XMLDTDContentModelSource getDTDContentModelSource() {
return fDTDContentModelSource;
} // getDTDContentModelSource(): XMLDTDContentModelSource
/**
* The start of a content model. Depending on the type of the content
* model, specific methods may be called between the call to the
* startContentModel method and the call to the endContentModel method.
*
* @param elementName The name of the element.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void startContentModel(String elementName, Augmentations augs)
throws XNIException {
if (fValidation) {
fDTDElementDeclName = elementName;
fMixedElementTypes.removeAllElements();
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.startContentModel(elementName, augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.startContentModel(elementName, augs);
}
} // startContentModel(String)
/**
* A content model of ANY.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #empty
* @see #startGroup
*/
public void any(Augmentations augs) throws XNIException {
if(fDTDGrammar != null)
fDTDGrammar.any(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.any(augs);
}
} // any()
/**
* A content model of EMPTY.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #any
* @see #startGroup
*/
public void empty(Augmentations augs) throws XNIException {
if(fDTDGrammar != null)
fDTDGrammar.empty(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.empty(augs);
}
} // empty()
/**
* A start of either a mixed or children content model. A mixed
* content model will immediately be followed by a call to the
* <code>pcdata()</code> method. A children content model will
* contain additional groups and/or elements.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #any
* @see #empty
*/
public void startGroup(Augmentations augs) throws XNIException {
fMixed = false;
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.startGroup(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.startGroup(augs);
}
} // startGroup()
/**
* The appearance of "#PCDATA" within a group signifying a
* mixed content model. This method will be the first called
* following the content model's <code>startGroup()</code>.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #startGroup
*/
public void pcdata(Augmentations augs) {
fMixed = true;
if(fDTDGrammar != null)
fDTDGrammar.pcdata(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.pcdata(augs);
}
} // pcdata()
/**
* A referenced element in a mixed or children content model.
*
* @param elementName The name of the referenced element.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void element(String elementName, Augmentations augs) throws XNIException {
// check VC: No duplicate Types, in a single mixed-content declaration
if (fMixed && fValidation) {
if (fMixedElementTypes.contains(elementName)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"DuplicateTypeInMixedContent",
new Object[]{fDTDElementDeclName, elementName},
XMLErrorReporter.SEVERITY_ERROR);
}
else {
fMixedElementTypes.addElement(elementName);
}
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.element(elementName, augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.element(elementName, augs);
}
} // childrenElement(String)
/**
* The separator between choices or sequences of a mixed or children
* content model.
*
* @param separator The type of children separator.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #SEPARATOR_CHOICE
* @see #SEPARATOR_SEQUENCE
*/
public void separator(short separator, Augmentations augs)
throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.separator(separator, augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.separator(separator, augs);
}
} // separator(short)
/**
* The occurrence count for a child in a children content model or
* for the mixed content model group.
*
* @param occurrence The occurrence count for the last element
* or group.
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*
* @see #OCCURS_ZERO_OR_ONE
* @see #OCCURS_ZERO_OR_MORE
* @see #OCCURS_ONE_OR_MORE
*/
public void occurrence(short occurrence, Augmentations augs)
throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.occurrence(occurrence, augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.occurrence(occurrence, augs);
}
} // occurrence(short)
/**
* The end of a group for mixed or children content models.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endGroup(Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.endGroup(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.endGroup(augs);
}
} // endGroup()
/**
* The end of a content model.
*
* @param augs Additional information that may include infoset
* augmentations.
*
* @throws XNIException Thrown by handler to signal an error.
*/
public void endContentModel(Augmentations augs) throws XNIException {
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.endContentModel(augs);
if (fDTDContentModelHandler != null) {
fDTDContentModelHandler.endContentModel(augs);
}
} // endContentModel()
//
// Private methods
//
/**
* Normalize the attribute value of a non CDATA default attribute
* collapsing sequences of space characters (x20)
*
* @param value The value to normalize
* @return Whether the value was changed or not.
*/
private boolean normalizeDefaultAttrValue(XMLString value) {
int oldLength = value.length;
boolean skipSpace = true; // skip leading spaces
int current = value.offset;
int end = value.offset + value.length;
for (int i = value.offset; i < end; i++) {
if (value.ch[i] == ' ') {
if (!skipSpace) {
// take the first whitespace as a space and skip the others
value.ch[current++] = ' ';
skipSpace = true;
}
else {
// just skip it.
}
}
else {
// simply shift non space chars if needed
if (current != i) {
value.ch[current] = value.ch[i];
}
current++;
skipSpace = false;
}
}
if (current != end) {
if (skipSpace) {
// if we finished on a space trim it
current--;
}
// set the new value length
value.length = current - value.offset;
return true;
}
return false;
}
/** initialization */
private void init() {
// datatype validators
if (fValidation) {
if (fNotationEnumVals == null) {
fNotationEnumVals = new Hashtable();
}
fNotationEnumVals.clear();
fTableOfIDAttributeNames = new Hashtable();
fTableOfNOTATIONAttributeNames = new Hashtable();
}
} // init()
protected boolean isValidNmtoken(String nmtoken) {
return XMLChar.isValidNmtoken(nmtoken);
} // isValidNmtoken(String): boolean
protected boolean isValidName(String name) {
return XMLChar.isValidName(name);
} // isValidName(String): boolean
} // class XMLDTDProcessor
| true | true | public void attributeDecl(String elementName, String attributeName,
String type, String[] enumeration,
String defaultType, XMLString defaultValue,
XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException {
if (type != XMLSymbols.fCDATASymbol && defaultValue != null) {
normalizeDefaultAttrValue(defaultValue);
}
if (fValidation) {
boolean duplicateAttributeDef = false ;
//Get Grammar index to grammar array
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar:fGrammarBucket.getActiveGrammar());
int elementIndex = grammar.getElementDeclIndex( elementName);
if (grammar.getAttributeDeclIndex(elementIndex, attributeName) != -1) {
//more than one attribute definition is provided for the same attribute of a given element type.
duplicateAttributeDef = true ;
//this feature works only when validation is true.
if(fWarnDuplicateAttdef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ATTRIBUTE_DEFINITION",
new Object[]{ elementName, attributeName },
XMLErrorReporter.SEVERITY_WARNING );
}
}
//
// a) VC: One ID per Element Type, If duplicate ID attribute
// b) VC: ID attribute Default. if there is a declareared attribute
// default for ID it should be of type #IMPLIED or #REQUIRED
if (type == XMLSymbols.fIDSymbol) {
if (defaultValue != null && defaultValue.length != 0) {
if (defaultType == null ||
!(defaultType == XMLSymbols.fIMPLIEDSymbol ||
defaultType == XMLSymbols.fREQUIREDSymbol)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"IDDefaultTypeInvalid",
new Object[]{ attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
if (!fTableOfIDAttributeNames.containsKey(elementName)) {
fTableOfIDAttributeNames.put(elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true,
// one typical case where this could be a problem, when any XML file
// provide the ID type information through internal subset so that it is available to the parser which read
//only internal subset. Now that attribute declaration(ID Type) can again be part of external parsed entity
//referenced. At that time if parser doesn't make this distinction it will throw an error for VC One ID per
//Element Type, which (second defintion) actually should be ignored. Application behavior may differ on the
//basis of error or warning thrown. - nb.
if(!duplicateAttributeDef){
String previousIDAttributeName = (String)fTableOfIDAttributeNames.get( elementName );//rule a)
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_ID_ATTRIBUTE",
new Object[]{ elementName, previousIDAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
//
// VC: One Notaion Per Element Type, should check if there is a
// duplicate NOTATION attribute
if (type == XMLSymbols.fNOTATIONSymbol) {
// VC: Notation Attributes: all notation names in the
// (attribute) declaration must be declared.
for (int i=0; i<enumeration.length; i++) {
fNotationEnumVals.put(enumeration[i], attributeName);
}
if (fTableOfNOTATIONAttributeNames.containsKey( elementName ) == false) {
fTableOfNOTATIONAttributeNames.put( elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true, Application behavior may differ on the basis of error or
//warning thrown. - nb.
if(!duplicateAttributeDef){
String previousNOTATIONAttributeName = (String) fTableOfNOTATIONAttributeNames.get( elementName );
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE",
new Object[]{ elementName, previousNOTATIONAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// VC: No Duplicate Tokens
// XML 1.0 SE Errata - E2
if (type == XMLSymbols.fENUMERATIONSymbol || type == XMLSymbols.fNOTATIONSymbol) {
outer:
for (int i = 0; i < enumeration.length; ++i) {
for (int j = i + 1; j < enumeration.length; ++j) {
if (enumeration[i].equals(enumeration[j])) {
// Only report the first uniqueness violation. There could be others,
// but additional overhead would be incurred tracking unique tokens
// that have already been encountered. -- mrglavas
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
type == XMLSymbols.fENUMERATIONSymbol
? "MSG_DISTINCT_TOKENS_IN_ENUMERATION"
: "MSG_DISTINCT_NOTATION_IN_ENUMERATION",
new Object[]{ elementName, enumeration[i], attributeName },
XMLErrorReporter.SEVERITY_ERROR);
break outer;
}
}
}
}
// VC: Attribute Default Legal
boolean ok = true;
if (defaultValue != null &&
(defaultType == null ||
(defaultType != null && defaultType == XMLSymbols.fFIXEDSymbol))) {
String value = defaultValue.toString();
if (type == XMLSymbols.fNMTOKENSSymbol ||
type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
StringTokenizer tokenizer = new StringTokenizer(value);
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (type == XMLSymbols.fNMTOKENSSymbol) {
if (!isValidNmtoken(nmtoken)) {
ok = false;
break;
}
}
else if (type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
if (!isValidName(nmtoken)) {
ok = false;
break;
}
}
if (!tokenizer.hasMoreTokens()) {
break;
}
}
}
}
else {
if (type == XMLSymbols.fENTITYSymbol ||
type == XMLSymbols.fIDSymbol ||
type == XMLSymbols.fIDREFSymbol ||
type == XMLSymbols.fNOTATIONSymbol) {
if (!isValidName(value)) {
ok = false;
}
}
else if (type == XMLSymbols.fNMTOKENSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
if (!isValidNmtoken(value)) {
ok = false;
}
}
if (type == XMLSymbols.fNOTATIONSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
ok = false;
for (int i=0; i<enumeration.length; i++) {
if (defaultValue.equals(enumeration[i])) {
ok = true;
}
}
}
}
if (!ok) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_ATT_DEFAULT_INVALID",
new Object[]{attributeName, value},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
if (fDTDHandler != null) {
fDTDHandler.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
}
} // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations)
| public void attributeDecl(String elementName, String attributeName,
String type, String[] enumeration,
String defaultType, XMLString defaultValue,
XMLString nonNormalizedDefaultValue, Augmentations augs) throws XNIException {
if (type != XMLSymbols.fCDATASymbol && defaultValue != null) {
normalizeDefaultAttrValue(defaultValue);
}
if (fValidation) {
boolean duplicateAttributeDef = false ;
//Get Grammar index to grammar array
DTDGrammar grammar = (fDTDGrammar != null? fDTDGrammar:fGrammarBucket.getActiveGrammar());
int elementIndex = grammar.getElementDeclIndex( elementName);
if (grammar.getAttributeDeclIndex(elementIndex, attributeName) != -1) {
//more than one attribute definition is provided for the same attribute of a given element type.
duplicateAttributeDef = true ;
//this feature works only when validation is true.
if(fWarnDuplicateAttdef){
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_DUPLICATE_ATTRIBUTE_DEFINITION",
new Object[]{ elementName, attributeName },
XMLErrorReporter.SEVERITY_WARNING );
}
}
//
// a) VC: One ID per Element Type, If duplicate ID attribute
// b) VC: ID attribute Default. if there is a declareared attribute
// default for ID it should be of type #IMPLIED or #REQUIRED
if (type == XMLSymbols.fIDSymbol) {
if (defaultValue != null && defaultValue.length != 0) {
if (defaultType == null ||
!(defaultType == XMLSymbols.fIMPLIEDSymbol ||
defaultType == XMLSymbols.fREQUIREDSymbol)) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"IDDefaultTypeInvalid",
new Object[]{ attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
if (!fTableOfIDAttributeNames.containsKey(elementName)) {
fTableOfIDAttributeNames.put(elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true,
// one typical case where this could be a problem, when any XML file
// provide the ID type information through internal subset so that it is available to the parser which read
//only internal subset. Now that attribute declaration(ID Type) can again be part of external parsed entity
//referenced. At that time if parser doesn't make this distinction it will throw an error for VC One ID per
//Element Type, which (second defintion) actually should be ignored. Application behavior may differ on the
//basis of error or warning thrown. - nb.
if(!duplicateAttributeDef){
String previousIDAttributeName = (String)fTableOfIDAttributeNames.get( elementName );//rule a)
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_ID_ATTRIBUTE",
new Object[]{ elementName, previousIDAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
//
// VC: One Notaion Per Element Type, should check if there is a
// duplicate NOTATION attribute
if (type == XMLSymbols.fNOTATIONSymbol) {
// VC: Notation Attributes: all notation names in the
// (attribute) declaration must be declared.
for (int i=0; i<enumeration.length; i++) {
fNotationEnumVals.put(enumeration[i], attributeName);
}
if (fTableOfNOTATIONAttributeNames.containsKey( elementName ) == false) {
fTableOfNOTATIONAttributeNames.put( elementName, attributeName);
}
else {
//we should not report an error, when there is duplicate attribute definition for given element type
//according to XML 1.0 spec, When more than one definition is provided for the same attribute of a given
//element type, the first declaration is binding and later declaration are *ignored*. So processor should
//ignore the second declarations, however an application would be warned of the duplicate attribute defintion
// if http://apache.org/xml/features/validation/warn-on-duplicate-attdef feature is set to true, Application behavior may differ on the basis of error or
//warning thrown. - nb.
if(!duplicateAttributeDef){
String previousNOTATIONAttributeName = (String) fTableOfNOTATIONAttributeNames.get( elementName );
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE",
new Object[]{ elementName, previousNOTATIONAttributeName, attributeName},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// VC: No Duplicate Tokens
// XML 1.0 SE Errata - E2
if (type == XMLSymbols.fENUMERATIONSymbol || type == XMLSymbols.fNOTATIONSymbol) {
outer:
for (int i = 0; i < enumeration.length; ++i) {
for (int j = i + 1; j < enumeration.length; ++j) {
if (enumeration[i].equals(enumeration[j])) {
// Only report the first uniqueness violation. There could be others,
// but additional overhead would be incurred tracking unique tokens
// that have already been encountered. -- mrglavas
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
type == XMLSymbols.fENUMERATIONSymbol
? "MSG_DISTINCT_TOKENS_IN_ENUMERATION"
: "MSG_DISTINCT_NOTATION_IN_ENUMERATION",
new Object[]{ elementName, enumeration[i], attributeName },
XMLErrorReporter.SEVERITY_ERROR);
break outer;
}
}
}
}
// VC: Attribute Default Legal
boolean ok = true;
if (defaultValue != null &&
(defaultType == null ||
(defaultType != null && defaultType == XMLSymbols.fFIXEDSymbol))) {
String value = defaultValue.toString();
if (type == XMLSymbols.fNMTOKENSSymbol ||
type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
StringTokenizer tokenizer = new StringTokenizer(value," ");
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (type == XMLSymbols.fNMTOKENSSymbol) {
if (!isValidNmtoken(nmtoken)) {
ok = false;
break;
}
}
else if (type == XMLSymbols.fENTITIESSymbol ||
type == XMLSymbols.fIDREFSSymbol) {
if (!isValidName(nmtoken)) {
ok = false;
break;
}
}
if (!tokenizer.hasMoreTokens()) {
break;
}
}
}
}
else {
if (type == XMLSymbols.fENTITYSymbol ||
type == XMLSymbols.fIDSymbol ||
type == XMLSymbols.fIDREFSymbol ||
type == XMLSymbols.fNOTATIONSymbol) {
if (!isValidName(value)) {
ok = false;
}
}
else if (type == XMLSymbols.fNMTOKENSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
if (!isValidNmtoken(value)) {
ok = false;
}
}
if (type == XMLSymbols.fNOTATIONSymbol ||
type == XMLSymbols.fENUMERATIONSymbol) {
ok = false;
for (int i=0; i<enumeration.length; i++) {
if (defaultValue.equals(enumeration[i])) {
ok = true;
}
}
}
}
if (!ok) {
fErrorReporter.reportError(XMLMessageFormatter.XML_DOMAIN,
"MSG_ATT_DEFAULT_INVALID",
new Object[]{attributeName, value},
XMLErrorReporter.SEVERITY_ERROR);
}
}
}
// call handlers
if(fDTDGrammar != null)
fDTDGrammar.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
if (fDTDHandler != null) {
fDTDHandler.attributeDecl(elementName, attributeName,
type, enumeration,
defaultType, defaultValue, nonNormalizedDefaultValue, augs);
}
} // attributeDecl(String,String,String,String[],String,XMLString, XMLString, Augmentations)
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/FieldInputLevel.java b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/FieldInputLevel.java
index e3fd72cc1..3140ca737 100644
--- a/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/FieldInputLevel.java
+++ b/src/DVN-EJB/src/java/edu/harvard/hmdc/vdcnet/study/FieldInputLevel.java
@@ -1,65 +1,65 @@
/*
* FieldInputLevel.java
*
* Created on August 4, 2006, 3:08 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.hmdc.vdcnet.study;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.GenerationType;
/**
* Defines the type of input for a study field:
* Required, Recommended, Optional
* @author Ellen Kraffmiller
*/
@Entity
public class FieldInputLevel {
@SequenceGenerator(name="fieldinputlevel_gen", sequenceName="fieldinputlevel_id_seq")
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="fieldinputlevel_gen")
private Long id;
private String name;
/** Creates a new instance of FieldInputLevel */
public FieldInputLevel() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int hashCode() {
int hash = 0;
hash += (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
- if (!(object instanceof StudyLock)) {
+ if (!(object instanceof FieldInputLevel)) {
return false;
}
FieldInputLevel other = (FieldInputLevel)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
}
| true | true | public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StudyLock)) {
return false;
}
FieldInputLevel other = (FieldInputLevel)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
| public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof FieldInputLevel)) {
return false;
}
FieldInputLevel other = (FieldInputLevel)object;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) return false;
return true;
}
|
diff --git a/htroot/yacysearchitem.java b/htroot/yacysearchitem.java
index f351cdae2..aec533f4a 100644
--- a/htroot/yacysearchitem.java
+++ b/htroot/yacysearchitem.java
@@ -1,225 +1,225 @@
// yacysearchitem.java
// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 28.08.2007 on http://yacy.net
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
// $LastChangedRevision: 1986 $
// $LastChangedBy: orbiter $
//
// LICENSE
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.TreeSet;
import de.anomic.http.httpRequestHeader;
import de.anomic.plasma.plasmaProfiling;
import de.anomic.plasma.plasmaSearchEvent;
import de.anomic.plasma.plasmaSearchQuery;
import de.anomic.plasma.plasmaSearchRankingProcess;
import de.anomic.plasma.plasmaSnippetCache;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverObjects;
import de.anomic.server.serverProfiling;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
import de.anomic.tools.nxTools;
import de.anomic.tools.Formatter;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacySeed;
import de.anomic.yacy.yacyURL;
public class yacysearchitem {
private static boolean col = true;
private static final int namelength = 60;
private static final int urllength = 120;
public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final plasmaSearchQuery theQuery = theSearch.getQuery();
// dynamically update count values
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1);
prop.put("totalcount", Formatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) {
// text search
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
yacyURL faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.webIndex.peers().newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", plasmaSwitchboard.dateString(result.modified()));
prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified()));
prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
yacyURL wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) +
((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
- final String desc = snippet.getLineMarked(theQuery.fullqueryHashes);
- prop.put("content_description", (snippet == null) ? "" : desc);
- prop.putXML("content_description-xml", (snippet == null) ? "" : desc);
- prop.putJSON("content_description-json", (snippet == null) ? "" : desc);
+ final String desc = (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes);
+ prop.put("content_description", desc);
+ prop.putXML("content_description-xml", desc);
+ prop.putJSON("content_description-json", desc);
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0), false);
return prop;
}
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
if (ms == null) {
prop.put("content_items", "0");
} else {
prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false));
prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_items_0_name", shorten(ms.name, namelength));
prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_items_0_source", ms.source.toNormalform(true, false));
prop.put("content_items_0_sourcedom", ms.source.getHost());
prop.put("content_items", 1);
}
return prop;
}
if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) {
// any other media content
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
plasmaSnippetCache.MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
private static String shorten(final String s, final int length) {
if (s.length() <= length) return s;
final int p = s.lastIndexOf('.');
if (p < 0) return s.substring(0, length - 3) + "...";
return s.substring(0, length - (s.length() - p) - 3) + "..." + s.substring(p);
}
private static String sizename(int size) {
if (size < 1024) return size + " bytes";
size = size / 1024;
if (size < 1024) return size + " kbyte";
size = size / 1024;
if (size < 1024) return size + " mbyte";
size = size / 1024;
return size + " gbyte";
}
}
| true | true | public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final plasmaSearchQuery theQuery = theSearch.getQuery();
// dynamically update count values
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1);
prop.put("totalcount", Formatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) {
// text search
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
yacyURL faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.webIndex.peers().newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", plasmaSwitchboard.dateString(result.modified()));
prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified()));
prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
yacyURL wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) +
((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
final String desc = snippet.getLineMarked(theQuery.fullqueryHashes);
prop.put("content_description", (snippet == null) ? "" : desc);
prop.putXML("content_description-xml", (snippet == null) ? "" : desc);
prop.putJSON("content_description-json", (snippet == null) ? "" : desc);
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0), false);
return prop;
}
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
if (ms == null) {
prop.put("content_items", "0");
} else {
prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false));
prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_items_0_name", shorten(ms.name, namelength));
prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_items_0_source", ms.source.toNormalform(true, false));
prop.put("content_items_0_sourcedom", ms.source.getHost());
prop.put("content_items", 1);
}
return prop;
}
if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) {
// any other media content
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
plasmaSnippetCache.MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
| public static serverObjects respond(final httpRequestHeader header, final serverObjects post, final serverSwitch<?> env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
final serverObjects prop = new serverObjects();
final String eventID = post.get("eventID", "");
final boolean authenticated = sb.adminAuthenticated(header) >= 2;
final int item = post.getInt("item", -1);
final boolean auth = ((String) header.get(httpRequestHeader.CONNECTION_PROP_CLIENTIP, "")).equals("localhost") || sb.verifyAuthentication(header, true);
final int display = (post == null) ? 0 : post.getInt("display", 0);
// default settings for blank item
prop.put("content", "0");
prop.put("rss", "0");
prop.put("references", "0");
prop.put("rssreferences", "0");
prop.put("dynamic", "0");
// find search event
final plasmaSearchEvent theSearch = plasmaSearchEvent.getEvent(eventID);
if (theSearch == null) {
// the event does not exist, show empty page
return prop;
}
final plasmaSearchQuery theQuery = theSearch.getQuery();
// dynamically update count values
final int offset = theQuery.neededResults() - theQuery.displayResults() + 1;
prop.put("offset", offset);
prop.put("itemscount", (item < 0) ? theQuery.neededResults() : item + 1);
prop.put("totalcount", Formatter.number(theSearch.getRankingResult().getLocalResourceSize() + theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("localResourceSize", Formatter.number(theSearch.getRankingResult().getLocalResourceSize(), true));
prop.put("remoteResourceSize", Formatter.number(theSearch.getRankingResult().getRemoteResourceSize(), true));
prop.put("remoteIndexCount", Formatter.number(theSearch.getRankingResult().getRemoteIndexCount(), true));
prop.put("remotePeerCount", Formatter.number(theSearch.getRankingResult().getRemotePeerCount(), true));
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) {
// text search
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
final int port=result.url().getPort();
yacyURL faviconURL = null;
if (!result.url().isLocal()) try {
faviconURL = new yacyURL(result.url().getProtocol() + "://" + result.url().getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico", null);
} catch (final MalformedURLException e1) {
faviconURL = null;
}
prop.put("content", 1); // switch on specific content
prop.put("content_authorized", authenticated ? "1" : "0");
prop.put("content_authorized_recommend", (sb.webIndex.peers().newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.urlstring()) == null) ? "1" : "0");
prop.putHTML("content_authorized_recommend_deletelink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&deleteref=" + result.hash() + "&urlmaskfilter=.*");
prop.putHTML("content_authorized_recommend_recommendlink", "/yacysearch.html?search=" + theQuery.queryString + "&Enter=Search&count=" + theQuery.displayResults() + "&offset=" + (theQuery.neededResults() - theQuery.displayResults()) + "&order=" + crypt.simpleEncode(theQuery.ranking.toExternalString()) + "&resource=local&time=3&recommendref=" + result.hash() + "&urlmaskfilter=.*");
prop.put("content_authorized_urlhash", result.hash());
prop.putHTML("content_title", result.title());
prop.putXML("content_title-xml", result.title());
prop.putJSON("content_title-json", result.title());
prop.putHTML("content_link", result.urlstring());
prop.put("content_display", display);
prop.putHTML("content_faviconCode", sb.licensedURLs.aquireLicense(faviconURL)); // aquire license for favicon url loading
prop.put("content_urlhash", result.hash());
prop.put("content_urlhexhash", yacySeed.b64Hash2hexHash(result.hash()));
prop.putHTML("content_urlname", nxTools.shortenURLString(result.urlname(), urllength));
prop.put("content_date", plasmaSwitchboard.dateString(result.modified()));
prop.put("content_date822", plasmaSwitchboard.dateString822(result.modified()));
prop.put("content_ybr", plasmaSearchRankingProcess.ybr(result.hash()));
prop.putHTML("content_size", Integer.toString(result.filesize())); // we don't use putNUM here because that number shall be usable as sorting key. To print the size, use 'sizename'
prop.putHTML("content_sizename", sizename(result.filesize()));
prop.putHTML("content_host", result.url().getHost());
prop.putHTML("content_file", result.url().getFile());
prop.putHTML("content_path", result.url().getPath());
prop.put("content_nl", (item == 0) ? 0 : 1);
final TreeSet<String>[] query = theQuery.queryWords();
yacyURL wordURL = null;
try {
prop.putHTML("content_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (final UnsupportedEncodingException e) {}
prop.putHTML("content_former", theQuery.queryString);
prop.put("content_rankingprops", result.word().toPropertyForm() + ", domLengthEstimated=" + yacyURL.domLengthEstimation(result.hash()) +
((yacyURL.probablyRootURL(result.hash())) ? ", probablyRootURL" : "") +
(((wordURL = yacyURL.probablyWordURL(result.hash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform(false, true) : ""));
final plasmaSnippetCache.TextSnippet snippet = result.textSnippet();
final String desc = (snippet == null) ? "" : snippet.getLineMarked(theQuery.fullqueryHashes);
prop.put("content_description", desc);
prop.putXML("content_description-xml", desc);
prop.putJSON("content_description-json", desc);
serverProfiling.update("SEARCH", new plasmaProfiling.searchEvent(theQuery.id(true), plasmaSearchEvent.FINALIZATION + "-" + item, 0, 0), false);
return prop;
}
if (theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) {
// image search; shows thumbnails
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final plasmaSnippetCache.MediaSnippet ms = theSearch.oneImage(item);
if (ms == null) {
prop.put("content_items", "0");
} else {
prop.putHTML("content_items_0_hrefCache", (auth) ? "/ViewImage.png?url=" + ms.href.toNormalform(true, false) : ms.href.toNormalform(true, false));
prop.putHTML("content_items_0_href", ms.href.toNormalform(true, false));
prop.put("content_items_0_code", sb.licensedURLs.aquireLicense(ms.href));
prop.putHTML("content_items_0_name", shorten(ms.name, namelength));
prop.put("content_items_0_attr", (ms.attr.equals("-1 x -1")) ? "" : "(" + ms.attr + ")"); // attributes, here: original size of image
prop.put("content_items_0_source", ms.source.toNormalform(true, false));
prop.put("content_items_0_sourcedom", ms.source.getHost());
prop.put("content_items", 1);
}
return prop;
}
if ((theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_AUDIO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_VIDEO) ||
(theQuery.contentdom == plasmaSearchQuery.CONTENTDOM_APP)) {
// any other media content
// generate result object
final plasmaSearchEvent.ResultEntry result = theSearch.oneResult(item);
if (result == null) return prop; // no content
prop.put("content", theQuery.contentdom + 1); // switch on specific content
final ArrayList<plasmaSnippetCache.MediaSnippet> media = result.mediaSnippets();
if (item == 0) col = true;
if (media != null) {
plasmaSnippetCache.MediaSnippet ms;
int c = 0;
for (int i = 0; i < media.size(); i++) {
ms = media.get(i);
prop.putHTML("content_items_" + i + "_href", ms.href.toNormalform(true, false));
prop.putHTML("content_items_" + i + "_hrefshort", nxTools.shortenURLString(ms.href.toNormalform(true, false), urllength));
prop.putHTML("content_items_" + i + "_name", shorten(ms.name, namelength));
prop.put("content_items_" + i + "_col", (col) ? "0" : "1");
c++;
col = !col;
}
prop.put("content_items", c);
} else {
prop.put("content_items", "0");
}
return prop;
}
return prop;
}
|
diff --git a/integration-beans/src/main/java/org/apache/mina/integration/beans/CharacterEditor.java b/integration-beans/src/main/java/org/apache/mina/integration/beans/CharacterEditor.java
index 1c68108e..45ad5610 100644
--- a/integration-beans/src/main/java/org/apache/mina/integration/beans/CharacterEditor.java
+++ b/integration-beans/src/main/java/org/apache/mina/integration/beans/CharacterEditor.java
@@ -1,56 +1,56 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.integration.beans;
import java.beans.PropertyEditor;
import java.util.regex.Pattern;
/**
* A {@link PropertyEditor} which converts a {@link String} into
* a {@link Character} and vice versa.
*
* @author The Apache MINA Project ([email protected])
* @version $Revision$, $Date$
*/
public class CharacterEditor extends AbstractPropertyEditor {
private static final Pattern UNICODE = Pattern.compile("\\\\[uU][0-9a-fA-F]+");
@Override
protected String toText(Object value) {
return String.valueOf(value);
}
@Override
protected Object toValue(String text) throws IllegalArgumentException {
- if (text.length() > 0) {
+ if (text.length() == 0) {
return Character.valueOf(Character.MIN_VALUE);
}
if (UNICODE.matcher(text).matches()) {
return Character.valueOf((char) Integer.parseInt(text.substring(2)));
}
if (text.length() != 1) {
throw new IllegalArgumentException("Too many characters: " + text);
}
return Character.valueOf(text.charAt(0));
}
}
| true | true | protected Object toValue(String text) throws IllegalArgumentException {
if (text.length() > 0) {
return Character.valueOf(Character.MIN_VALUE);
}
if (UNICODE.matcher(text).matches()) {
return Character.valueOf((char) Integer.parseInt(text.substring(2)));
}
if (text.length() != 1) {
throw new IllegalArgumentException("Too many characters: " + text);
}
return Character.valueOf(text.charAt(0));
}
| protected Object toValue(String text) throws IllegalArgumentException {
if (text.length() == 0) {
return Character.valueOf(Character.MIN_VALUE);
}
if (UNICODE.matcher(text).matches()) {
return Character.valueOf((char) Integer.parseInt(text.substring(2)));
}
if (text.length() != 1) {
throw new IllegalArgumentException("Too many characters: " + text);
}
return Character.valueOf(text.charAt(0));
}
|
diff --git a/src/main/java/com/endercreators/perms/EnderPerms.java b/src/main/java/com/endercreators/perms/EnderPerms.java
index 685847a..83a8d30 100644
--- a/src/main/java/com/endercreators/perms/EnderPerms.java
+++ b/src/main/java/com/endercreators/perms/EnderPerms.java
@@ -1,121 +1,121 @@
package com.endercreators.perms;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.List;
public class EnderPerms extends JavaPlugin {
private MySQLManager mysqlmanager;
public HashMap<String, List<String>> cachegroup = new HashMap<String, List<String>>();
public static Permission perms = null;
public static Chat chat = null;
@Override
public void onEnable() {
this.saveDefaultConfig();
- if ((!setupPermissions()) || (!setupChat())) {
+ if (!setupPermissions()) {
getLogger().info("Stopping plugin. Vault not found.");
return;
}
mysqlmanager = new MySQLManager(this);
if (getConfig().getLong("refresh") < 60)
getLogger().info("Warning: Refresh time is under 60 secs.");
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
refresh();
}
}, 60, getConfig().getLong("refresh") * 20);
}
public void go(Runnable runnable) {
Bukkit.getScheduler().runTaskLater(this, runnable, 0);
}
public MySQLManager getMySQLManager() {
return mysqlmanager;
}
public EnderPerms getPlugin() {
return this;
}
private boolean setupChat() {
RegisteredServiceProvider<Chat> rsp = getServer().getServicesManager().getRegistration(Chat.class);
chat = rsp.getProvider();
return chat != null;
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
perms = rsp.getProvider();
return perms != null;
}
@Override
public void onDisable() {
}
public void refresh() {
go(new Runnable() {
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
removeFromAllGroups(player);
}
for (Player player : Bukkit.getOnlinePlayers()) {
removeFromAllGroups(player);
String special = getMySQLManager().getGroup(player.getName());
if (special != null)
addToGroup(player, special);
addToGroup(player, getConfig().getString("default"));
}
}
});
}
public void addToGroup(Player player, String group) {
perms.playerAddGroup("NULL", player.getName(), group);
List<String> groups = cachegroup.get(player.getName());
groups.add(group);
cachegroup.remove(player.getName());
cachegroup.put(player.getName(), groups);
}
public void removeFromGroup(Player player, String group) {
perms.playerRemoveGroup("NULL", player.getName(), group);
List<String> groups = cachegroup.get(player.getName());
groups.remove(group);
cachegroup.remove(player.getName());
cachegroup.put(player.getName(), groups);
}
public void removeFromAllGroups(Player player) {
List<String> groups = cachegroup.get(player.getName());
for (String group : groups) {
removeFromGroup(player, group);
}
cachegroup.remove(player.getName());
}
public List<String> getGroups() {
return getConfig().getStringList("groups");
}
}
| true | true | public void onEnable() {
this.saveDefaultConfig();
if ((!setupPermissions()) || (!setupChat())) {
getLogger().info("Stopping plugin. Vault not found.");
return;
}
mysqlmanager = new MySQLManager(this);
if (getConfig().getLong("refresh") < 60)
getLogger().info("Warning: Refresh time is under 60 secs.");
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
refresh();
}
}, 60, getConfig().getLong("refresh") * 20);
}
| public void onEnable() {
this.saveDefaultConfig();
if (!setupPermissions()) {
getLogger().info("Stopping plugin. Vault not found.");
return;
}
mysqlmanager = new MySQLManager(this);
if (getConfig().getLong("refresh") < 60)
getLogger().info("Warning: Refresh time is under 60 secs.");
Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
public void run() {
refresh();
}
}, 60, getConfig().getLong("refresh") * 20);
}
|
diff --git a/src/jp/co/qsdn/android/iwashi3d/AtlantisService.java b/src/jp/co/qsdn/android/iwashi3d/AtlantisService.java
index b1c708c..b6c66fd 100644
--- a/src/jp/co/qsdn/android/iwashi3d/AtlantisService.java
+++ b/src/jp/co/qsdn/android/iwashi3d/AtlantisService.java
@@ -1,559 +1,559 @@
/*
* Copyright (C) 2011 QSDN,Inc.
* Copyright (C) 2011 Atsushi Konno
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.co.qsdn.android.iwashi3d;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.wallpaper.WallpaperService;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;
import jp.co.qsdn.android.iwashi3d.GLRenderer;
import jp.co.qsdn.android.iwashi3d.util.MatrixTrackingGL;
public class AtlantisService extends WallpaperService {
private static final String TAG = AtlantisService.class.getName();
private static final boolean _debug = false;
private static final int RETRY_COUNT = 3;
private class AtlantisEngine extends Engine {
private final String TAG = AtlantisEngine.class.getName();
private int width = 0;
private int height = 0;
private boolean binded = false;
private boolean mInitialized = false;
/* EGL関連は毎回再作成?? */
private MatrixTrackingGL gl10 = null;
private EGL10 egl10 = null;
private EGLContext eglContext = null;
private EGLDisplay eglDisplay = null;
private EGLSurface eglSurface = null;
private GLRenderer glRenderer = null;
private ExecutorService getExecutor() {
if (executor == null) {
executor = Executors.newSingleThreadExecutor();
}
return executor;
}
private ExecutorService executor = null;
private Runnable drawCommand = null;
@Override
public void onCreate(final SurfaceHolder holder) {
if (_debug) Log.d(TAG, "start onCreate() [" + this + "]");
super.onCreate(holder);
/*=====================================================================*/
/* 携帯電話として機能しなくなるので */
/* タッチイベントは無効にしておく. */
/* 画面の空いたところのタッチにだけ反応したいので */
/* Engine.onCommandで対応する */
/*=====================================================================*/
setTouchEventsEnabled(false);
if (! isPreview()) {
AtlantisNotification.putNotice(AtlantisService.this);
}
if (_debug) Log.d(TAG, "end onCreate() [" + this + "]");
}
@Override
public void onDestroy() {
if (_debug) Log.d(TAG, "start onDestroy() [" + this + "]");
if (! isPreview()) {
AtlantisNotification.removeNotice(getApplicationContext());
}
else {
}
super.onDestroy();
System.gc();
if (_debug) Log.d(TAG, "end onDestroy() [" + this + "]");
}
private void doExecute(Runnable command) {
while(true) {
try {
getExecutor().execute(command);
}
catch (RejectedExecutionException e) {
if (getExecutor().isShutdown()) {
// ignore
}
else {
Log.e(TAG, "command execute failure", e);
waitNano();
System.gc();
continue;
}
}
break;
}
}
int[][] configSpec = {
{
// RGB565 color
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE,6,
EGL10.EGL_BLUE_SIZE, 5,
EGL10.EGL_ALPHA_SIZE, EGL10.EGL_DONT_CARE,
EGL10.EGL_DEPTH_SIZE, 24,
EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
// window (and not a pixmap or a pbuffer)
EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT,
EGL10.EGL_NONE ,
},
{
// RGB565 color
EGL10.EGL_RED_SIZE, 5,
EGL10.EGL_GREEN_SIZE,6,
EGL10.EGL_BLUE_SIZE,5,
EGL10.EGL_ALPHA_SIZE, EGL10.EGL_DONT_CARE,
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_STENCIL_SIZE, EGL10.EGL_DONT_CARE,
// window (and not a pixmap or a pbuffer)
EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT,
EGL10.EGL_NONE ,
},
{
EGL10.EGL_NONE,
}
};
@Override
public void onSurfaceCreated(final SurfaceHolder holder) {
if (_debug) Log.d(TAG, "start onSurfaceCreated() [" + this + "]");
super.onSurfaceCreated(holder);
Runnable surfaceCreatedCommand = new Runnable() {
@Override
public void run() {
if (mInitialized) {
if (_debug) Log.d(TAG, "already Initialized(surfaceCreatedCommand)");
return;
}
boolean ret;
/* OpenGLの初期化 */
int counter = 0;
int specCounter = 0;
while(true) {
if (_debug) Log.d(TAG, "start EGLContext.getEGL()");
exitEgl();
egl10 = (EGL10) EGLContext.getEGL();
if (_debug) Log.d(TAG, "end EGLContext.getEGL()");
if (_debug) Log.d(TAG, "start eglGetDisplay");
eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (_debug) Log.d(TAG, "end eglGetDisplay");
if (eglDisplay == null || EGL10.EGL_NO_DISPLAY.equals(eglDisplay)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "eglGetDisplayがEGL_NO_DISPLAY [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_DISPLAY");
throw new RuntimeException("OpenGL Error(EGL_NO_DISPLAY) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
{
egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
}
int[] version = new int[2];
if (! egl10.eglInitialize(eglDisplay, version)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglInitializeがfalse [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglInitializeがfalse");
throw new RuntimeException("OpenGL Error(eglInitialize) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfig = new int[1];
/*-----------------------------------------------------------------*/
/* 条件に見合うEGLConfigを取得 */
/*-----------------------------------------------------------------*/
egl10.eglChooseConfig(eglDisplay, configSpec[specCounter++], configs, 1, numConfig);
/*-----------------------------------------------------------------*/
/* もしEGLConfigが取得できなければ */
/*-----------------------------------------------------------------*/
if (numConfig[0] == 0) {
if (_debug) Log.d(TAG, "numConfig[0]=" + numConfig[0] + "");
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
errStr += " eglChooseConfig numConfig == 0 ";
- Log.e(TAG,"eglChooseConfig失敗:"
- + "numConfig:[" + numConfig[0] + "] errStr:[" + errStr + "]");
+ errStr += " numConfig:[" + numConfig[0] + "]:";
+ errStr += " configSpec:[" + (specCounter - 1) + "]:";
+ Log.e(TAG,"eglChooseConfig失敗:" + errStr);
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
- Log.e(TAG,"eglChooseConfig失敗:"
- + "numConfig:[" + numConfig[0] + "] errStr:[" + errStr + "]");
+ Log.e(TAG,"eglChooseConfig失敗:" + errStr);
throw new RuntimeException("OpenGL Error "
+ errStr + " :"
);
}
}
EGLConfig config = configs[0];
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLContext作成 */
/*-----------------------------------------------------------------*/
eglContext = egl10.eglCreateContext(eglDisplay, config, EGL10.EGL_NO_CONTEXT, null);
if (eglContext == null || EGL10.EGL_NO_CONTEXT.equals(eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateContext == EGL_NO_CONTEXT [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_CONTEXT");
throw new RuntimeException("OpenGL Error(EGL_NO_CONTEXT) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateContext done.");
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLSurface作成 */
/*-----------------------------------------------------------------*/
eglSurface = egl10.eglCreateWindowSurface(eglDisplay, config, holder, null);
if (eglSurface == null || EGL10.EGL_NO_SURFACE.equals(eglSurface)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateWindowSurface == EGL_NO_SURFACE [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateWindowSurfaceがEGL_NO_SURFACE");
throw new RuntimeException("OpenGL Error(EGL_NO_SURFACE) "
+ errStr + " :"
);
}
if (_debug) Log.e(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateWindowSurface done.");
/*-----------------------------------------------------------------*/
/* EGLContextとEGLSurfaceを関連付ける(アタッチ) */
/*-----------------------------------------------------------------*/
if (! egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglMakeCurrent == false [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglMakeCurrentがfalse");
throw new RuntimeException("OpenGL Error(eglMakeCurrent) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglMakeCurrent done.");
if (_debug) Log.d(TAG, "now create gl10 object");
gl10 = new MatrixTrackingGL((GL10) (eglContext.getGL()));
/*-----------------------------------------------------------------*/
/* Rendererの初期化 */
/*-----------------------------------------------------------------*/
glRenderer = GLRenderer.getInstance(getApplicationContext());
synchronized (glRenderer) {
glRenderer.onSurfaceCreated(gl10, config, getApplicationContext());
}
if (_debug) Log.d(TAG, "EGL initalize done.");
mInitialized = true;
if (drawCommand == null) {
drawCommand = new Runnable() {
public void run() {
if (mInitialized && glRenderer != null && gl10 != null) {
synchronized (glRenderer) {
glRenderer.onDrawFrame(gl10);
}
egl10.eglSwapBuffers(eglDisplay, eglSurface);
if (!getExecutor().isShutdown() && isVisible() && egl10.eglGetError() != EGL11.EGL_CONTEXT_LOST) {
doExecute(drawCommand);
}
}
}
};
doExecute(drawCommand);
}
break;
}
Log.d(TAG, "selected config spec for opengl is No." + counter);
}
};
doExecute(surfaceCreatedCommand);
if (_debug) Log.d(TAG, "end onSurfaceCreated() [" + this + "]");
}
@Override
public void onSurfaceDestroyed(final SurfaceHolder holder) {
if (_debug) Log.d(TAG, "start onSurfaceDestroyed() [" + this + "]");
Runnable surfaceDestroyedCommand = new Runnable() {
@Override
public void run() {
synchronized (glRenderer) {
glRenderer.onSurfaceDestroyed(gl10);
}
exitEgl();
gl10.shutdown();
gl10 = null;
System.gc();
mInitialized = false;
}
};
doExecute(surfaceDestroyedCommand);
getExecutor().shutdown();
try {
if (!getExecutor().awaitTermination(60, TimeUnit.SECONDS)) {
getExecutor().shutdownNow();
if (!getExecutor().awaitTermination(60, TimeUnit.SECONDS)) {
if (_debug) Log.d(TAG,"ExecutorService did not terminate....");
getExecutor().shutdownNow();
Thread.currentThread().interrupt();
}
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
drawCommand = null;
executor = null;
super.onSurfaceDestroyed(holder);
if (_debug) Log.d(TAG, "end onSurfaceDestroyed() [" + this + "]");
}
@Override
public void onSurfaceChanged(final SurfaceHolder holder, final int format, final int width, final int height) {
if (_debug) Log.d(TAG, "start onSurfaceChanged() [" + this + "]");
super.onSurfaceChanged(holder, format, width, height);
this.width = width;
this.height = height;
Runnable surfaceChangedCommand = new Runnable() {
public void run() {
if (glRenderer != null && gl10 != null && mInitialized) {
synchronized (glRenderer) {
glRenderer.onSurfaceChanged(gl10, width, height);
}
}
};
};
doExecute(surfaceChangedCommand);
if (_debug) Log.d(TAG, "end onSurfaceChanged() [" + this + "]");
}
@Override
public void onVisibilityChanged(final boolean visible) {
if (_debug) Log.d(TAG, "start onVisibilityChanged()");
super.onVisibilityChanged(visible);
/* サーフェスが見えるようになったよ! */
if (visible && drawCommand != null && mInitialized) {
/* 設定変更のタイミング */
if (glRenderer != null) {
synchronized (glRenderer) {
glRenderer.updateSetting(getApplicationContext());
}
}
doExecute(drawCommand);
}
if (_debug) Log.d(TAG, "end onVisibilityChanged()");
}
@Override
public void onOffsetsChanged(final float xOffset, final float yOffset,
final float xOffsetStep, final float yOffsetStep,
final int xPixelOffset, final int yPixelOffset) {
if (_debug) Log.d(TAG, "start onOffsetsChanged()");
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
if (xOffsetStep == 0.0f && yOffsetStep == 0.0f) {
if (_debug) Log.d(TAG, "end onOffsetChanged() no execute");
return;
}
Runnable offsetsChangedCommand = new Runnable() {
public void run() {
if (mInitialized && glRenderer != null && gl10 != null) {
synchronized (glRenderer) {
glRenderer.onOffsetsChanged(gl10, xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
}
}
};
};
doExecute(offsetsChangedCommand);
if (_debug) Log.d(TAG, "end onOffsetChanged()");
}
@Override
public Bundle onCommand(final String action, final int x, final int y, final int z, final Bundle extras, final boolean resultRequested){
if (_debug) {
Log.d(TAG, "start onCommand "
+ "action:[" + action + "]:"
+ "x:[" + x + "]:"
+ "y:[" + y + "]:"
+ "z:[" + z + "]:"
+ "extras:[" + extras + "]:"
+ "resultRequested:[" + resultRequested + "]:"
);
}
/*=====================================================================*/
/* 画面の何もないところへのタッチにだけ反応するため */
/* actionがandroid.wallpaper.tapのときだけ処理する */
/*=====================================================================*/
if (action.equals("android.wallpaper.tap")) {
Runnable onCommandCommand = new Runnable() {
public void run() {
if (mInitialized && glRenderer != null && gl10 != null) {
synchronized (glRenderer) {
glRenderer.onCommand(gl10, action, x, y, z, extras, resultRequested);
}
}
}
};
doExecute(onCommandCommand);
}
Bundle ret = super.onCommand(action, x, y, z, extras, resultRequested);
if (_debug) Log.d(TAG, "end onCommand");
return ret;
}
public void exitEgl() {
if (_debug) Log.d(TAG, "start exitEgl");
if (egl10 != null) {
if (eglDisplay != null && ! eglDisplay.equals(EGL10.EGL_NO_DISPLAY)) {
if (! egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT)) {
Log.e(TAG, "eglMakeCurrentがfalse [" + AtlantisService.getErrorString(egl10.eglGetError()) + "]");
}
if (eglSurface != null && ! eglSurface.equals(EGL10.EGL_NO_SURFACE)) {
if (! egl10.eglDestroySurface(eglDisplay, eglSurface)) {
Log.e(TAG, "eglDestroySurfaceがfalse [" + AtlantisService.getErrorString(egl10.eglGetError()) + "]");
}
eglSurface = null;
}
if (eglContext != null && ! eglContext.equals(EGL10.EGL_NO_CONTEXT)) {
if (! egl10.eglDestroyContext(eglDisplay, eglContext)) {
Log.e(TAG, "eglDestroyContextがfalse [" + AtlantisService.getErrorString(egl10.eglGetError()) + "]");
}
eglContext = null;
}
if (! egl10.eglTerminate(eglDisplay)) {
Log.e(TAG, "eglTerminateがfalse [" + AtlantisService.getErrorString(egl10.eglGetError()) + "]");
}
eglDisplay = null;
}
egl10 = null;
}
if (_debug) Log.d(TAG, "end exitEgl");
}
}
@Override
public Engine onCreateEngine() {
if (_debug) Log.d(TAG, "start onCreateEngine()");
AtlantisEngine engine = new AtlantisEngine();
if (_debug) Log.d(TAG, "engine:[" + engine + "]");
if (_debug) Log.d(TAG, "end onCreateEngine()");
return engine;
}
public void waitNano() {
if (_debug) Log.d(TAG, "start waitNano");
try {
//TimeUnit.NANOSECONDS.sleep(5000);
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
if (_debug) Log.d(TAG, "end waitNano");
}
public static String getErrorString(int err) {
switch (err) {
case EGL10.EGL_NOT_INITIALIZED:
return "EGL_NOT_INITIALIZED";
case EGL10.EGL_BAD_ACCESS:
return "EGL_BAD_ACCESS";
case EGL10.EGL_BAD_ALLOC:
return "EGL_BAD_ALLOC";
case EGL10.EGL_BAD_ATTRIBUTE:
return "EGL_BAD_ATTRIBUTE";
case EGL10.EGL_BAD_CONTEXT:
return "EGL_BAD_CONTEXT";
case EGL10.EGL_BAD_CONFIG:
return "EGL_BAD_CONFIG";
case EGL10.EGL_BAD_CURRENT_SURFACE:
return "EGL_BAD_CURRENT_SURFACE";
case EGL10.EGL_BAD_DISPLAY:
return "EGL_BAD_DISPLAY";
case EGL10.EGL_BAD_SURFACE:
return "EGL_BAD_SURFACE";
case EGL10.EGL_BAD_MATCH:
return "EGL_BAD_MATCH";
case EGL10.EGL_BAD_PARAMETER:
return "EGL_BAD_PARAMETER";
case EGL10.EGL_BAD_NATIVE_PIXMAP:
return "EGL_BAD_NATIVE_PIXMAP";
case EGL10.EGL_BAD_NATIVE_WINDOW:
return "EGL_BAD_NATIVE_WINDOW";
case EGL11.EGL_CONTEXT_LOST:
return "EGL_CONTEXT_LOST";
default:
return "OTHER err:[" + err + "]";
}
}
}
| false | true | public void onSurfaceCreated(final SurfaceHolder holder) {
if (_debug) Log.d(TAG, "start onSurfaceCreated() [" + this + "]");
super.onSurfaceCreated(holder);
Runnable surfaceCreatedCommand = new Runnable() {
@Override
public void run() {
if (mInitialized) {
if (_debug) Log.d(TAG, "already Initialized(surfaceCreatedCommand)");
return;
}
boolean ret;
/* OpenGLの初期化 */
int counter = 0;
int specCounter = 0;
while(true) {
if (_debug) Log.d(TAG, "start EGLContext.getEGL()");
exitEgl();
egl10 = (EGL10) EGLContext.getEGL();
if (_debug) Log.d(TAG, "end EGLContext.getEGL()");
if (_debug) Log.d(TAG, "start eglGetDisplay");
eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (_debug) Log.d(TAG, "end eglGetDisplay");
if (eglDisplay == null || EGL10.EGL_NO_DISPLAY.equals(eglDisplay)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "eglGetDisplayがEGL_NO_DISPLAY [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_DISPLAY");
throw new RuntimeException("OpenGL Error(EGL_NO_DISPLAY) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
{
egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
}
int[] version = new int[2];
if (! egl10.eglInitialize(eglDisplay, version)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglInitializeがfalse [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglInitializeがfalse");
throw new RuntimeException("OpenGL Error(eglInitialize) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfig = new int[1];
/*-----------------------------------------------------------------*/
/* 条件に見合うEGLConfigを取得 */
/*-----------------------------------------------------------------*/
egl10.eglChooseConfig(eglDisplay, configSpec[specCounter++], configs, 1, numConfig);
/*-----------------------------------------------------------------*/
/* もしEGLConfigが取得できなければ */
/*-----------------------------------------------------------------*/
if (numConfig[0] == 0) {
if (_debug) Log.d(TAG, "numConfig[0]=" + numConfig[0] + "");
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
errStr += " eglChooseConfig numConfig == 0 ";
Log.e(TAG,"eglChooseConfig失敗:"
+ "numConfig:[" + numConfig[0] + "] errStr:[" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"eglChooseConfig失敗:"
+ "numConfig:[" + numConfig[0] + "] errStr:[" + errStr + "]");
throw new RuntimeException("OpenGL Error "
+ errStr + " :"
);
}
}
EGLConfig config = configs[0];
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLContext作成 */
/*-----------------------------------------------------------------*/
eglContext = egl10.eglCreateContext(eglDisplay, config, EGL10.EGL_NO_CONTEXT, null);
if (eglContext == null || EGL10.EGL_NO_CONTEXT.equals(eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateContext == EGL_NO_CONTEXT [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_CONTEXT");
throw new RuntimeException("OpenGL Error(EGL_NO_CONTEXT) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateContext done.");
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLSurface作成 */
/*-----------------------------------------------------------------*/
eglSurface = egl10.eglCreateWindowSurface(eglDisplay, config, holder, null);
if (eglSurface == null || EGL10.EGL_NO_SURFACE.equals(eglSurface)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateWindowSurface == EGL_NO_SURFACE [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateWindowSurfaceがEGL_NO_SURFACE");
throw new RuntimeException("OpenGL Error(EGL_NO_SURFACE) "
+ errStr + " :"
);
}
if (_debug) Log.e(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateWindowSurface done.");
/*-----------------------------------------------------------------*/
/* EGLContextとEGLSurfaceを関連付ける(アタッチ) */
/*-----------------------------------------------------------------*/
if (! egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglMakeCurrent == false [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglMakeCurrentがfalse");
throw new RuntimeException("OpenGL Error(eglMakeCurrent) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglMakeCurrent done.");
if (_debug) Log.d(TAG, "now create gl10 object");
gl10 = new MatrixTrackingGL((GL10) (eglContext.getGL()));
/*-----------------------------------------------------------------*/
/* Rendererの初期化 */
/*-----------------------------------------------------------------*/
glRenderer = GLRenderer.getInstance(getApplicationContext());
synchronized (glRenderer) {
glRenderer.onSurfaceCreated(gl10, config, getApplicationContext());
}
if (_debug) Log.d(TAG, "EGL initalize done.");
mInitialized = true;
if (drawCommand == null) {
drawCommand = new Runnable() {
public void run() {
if (mInitialized && glRenderer != null && gl10 != null) {
synchronized (glRenderer) {
glRenderer.onDrawFrame(gl10);
}
egl10.eglSwapBuffers(eglDisplay, eglSurface);
if (!getExecutor().isShutdown() && isVisible() && egl10.eglGetError() != EGL11.EGL_CONTEXT_LOST) {
doExecute(drawCommand);
}
}
}
};
doExecute(drawCommand);
}
break;
}
Log.d(TAG, "selected config spec for opengl is No." + counter);
}
};
doExecute(surfaceCreatedCommand);
if (_debug) Log.d(TAG, "end onSurfaceCreated() [" + this + "]");
}
| public void onSurfaceCreated(final SurfaceHolder holder) {
if (_debug) Log.d(TAG, "start onSurfaceCreated() [" + this + "]");
super.onSurfaceCreated(holder);
Runnable surfaceCreatedCommand = new Runnable() {
@Override
public void run() {
if (mInitialized) {
if (_debug) Log.d(TAG, "already Initialized(surfaceCreatedCommand)");
return;
}
boolean ret;
/* OpenGLの初期化 */
int counter = 0;
int specCounter = 0;
while(true) {
if (_debug) Log.d(TAG, "start EGLContext.getEGL()");
exitEgl();
egl10 = (EGL10) EGLContext.getEGL();
if (_debug) Log.d(TAG, "end EGLContext.getEGL()");
if (_debug) Log.d(TAG, "start eglGetDisplay");
eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (_debug) Log.d(TAG, "end eglGetDisplay");
if (eglDisplay == null || EGL10.EGL_NO_DISPLAY.equals(eglDisplay)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "eglGetDisplayがEGL_NO_DISPLAY [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_DISPLAY");
throw new RuntimeException("OpenGL Error(EGL_NO_DISPLAY) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
{
egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
}
int[] version = new int[2];
if (! egl10.eglInitialize(eglDisplay, version)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglInitializeがfalse [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglInitializeがfalse");
throw new RuntimeException("OpenGL Error(eglInitialize) "
+ errStr + ": "
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfig = new int[1];
/*-----------------------------------------------------------------*/
/* 条件に見合うEGLConfigを取得 */
/*-----------------------------------------------------------------*/
egl10.eglChooseConfig(eglDisplay, configSpec[specCounter++], configs, 1, numConfig);
/*-----------------------------------------------------------------*/
/* もしEGLConfigが取得できなければ */
/*-----------------------------------------------------------------*/
if (numConfig[0] == 0) {
if (_debug) Log.d(TAG, "numConfig[0]=" + numConfig[0] + "");
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
errStr += " eglChooseConfig numConfig == 0 ";
errStr += " numConfig:[" + numConfig[0] + "]:";
errStr += " configSpec:[" + (specCounter - 1) + "]:";
Log.e(TAG,"eglChooseConfig失敗:" + errStr);
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"eglChooseConfig失敗:" + errStr);
throw new RuntimeException("OpenGL Error "
+ errStr + " :"
);
}
}
EGLConfig config = configs[0];
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLContext作成 */
/*-----------------------------------------------------------------*/
eglContext = egl10.eglCreateContext(eglDisplay, config, EGL10.EGL_NO_CONTEXT, null);
if (eglContext == null || EGL10.EGL_NO_CONTEXT.equals(eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateContext == EGL_NO_CONTEXT [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateContextがEGL_NO_CONTEXT");
throw new RuntimeException("OpenGL Error(EGL_NO_CONTEXT) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateContext done.");
/*-----------------------------------------------------------------*/
/* 取得したEGLDisplayとEGLConfigでEGLSurface作成 */
/*-----------------------------------------------------------------*/
eglSurface = egl10.eglCreateWindowSurface(eglDisplay, config, holder, null);
if (eglSurface == null || EGL10.EGL_NO_SURFACE.equals(eglSurface)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglCreateWindowSurface == EGL_NO_SURFACE [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG, "egl10.eglCreateWindowSurfaceがEGL_NO_SURFACE");
throw new RuntimeException("OpenGL Error(EGL_NO_SURFACE) "
+ errStr + " :"
);
}
if (_debug) Log.e(TAG, "RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglCreateWindowSurface done.");
/*-----------------------------------------------------------------*/
/* EGLContextとEGLSurfaceを関連付ける(アタッチ) */
/*-----------------------------------------------------------------*/
if (! egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
String errStr = AtlantisService.getErrorString(egl10.eglGetError());
if (_debug) Log.d(TAG, "egl10.eglMakeCurrent == false [" + errStr + "]");
exitEgl();
if (++counter >= AtlantisService.RETRY_COUNT) {
Log.e(TAG,"egl10.eglMakeCurrentがfalse");
throw new RuntimeException("OpenGL Error(eglMakeCurrent) "
+ errStr + " :"
);
}
if (_debug) Log.d(TAG,"RETRY");
System.gc();
waitNano();
continue;
}
if (_debug) Log.d(TAG, "eglMakeCurrent done.");
if (_debug) Log.d(TAG, "now create gl10 object");
gl10 = new MatrixTrackingGL((GL10) (eglContext.getGL()));
/*-----------------------------------------------------------------*/
/* Rendererの初期化 */
/*-----------------------------------------------------------------*/
glRenderer = GLRenderer.getInstance(getApplicationContext());
synchronized (glRenderer) {
glRenderer.onSurfaceCreated(gl10, config, getApplicationContext());
}
if (_debug) Log.d(TAG, "EGL initalize done.");
mInitialized = true;
if (drawCommand == null) {
drawCommand = new Runnable() {
public void run() {
if (mInitialized && glRenderer != null && gl10 != null) {
synchronized (glRenderer) {
glRenderer.onDrawFrame(gl10);
}
egl10.eglSwapBuffers(eglDisplay, eglSurface);
if (!getExecutor().isShutdown() && isVisible() && egl10.eglGetError() != EGL11.EGL_CONTEXT_LOST) {
doExecute(drawCommand);
}
}
}
};
doExecute(drawCommand);
}
break;
}
Log.d(TAG, "selected config spec for opengl is No." + counter);
}
};
doExecute(surfaceCreatedCommand);
if (_debug) Log.d(TAG, "end onSurfaceCreated() [" + this + "]");
}
|
diff --git a/genlab.algog.gui.examples/src/genlab/algog/gui/examples/examples/ExampleTestFunctionChakongHaimes.java b/genlab.algog.gui.examples/src/genlab/algog/gui/examples/examples/ExampleTestFunctionChakongHaimes.java
index fae8e13..80ab9dd 100644
--- a/genlab.algog.gui.examples/src/genlab/algog/gui/examples/examples/ExampleTestFunctionChakongHaimes.java
+++ b/genlab.algog.gui.examples/src/genlab/algog/gui/examples/examples/ExampleTestFunctionChakongHaimes.java
@@ -1,226 +1,226 @@
package genlab.algog.gui.examples.examples;
import genlab.algog.algos.meta.DoubleGeneAlgo;
import genlab.algog.algos.meta.GenomeAlgo;
import genlab.algog.algos.meta.GoalAlgo;
import genlab.algog.algos.meta.IntegerGeneAlgo;
import genlab.algog.algos.meta.NSGA2GeneticExplorationAlgo;
import genlab.algog.algos.meta.VerificationFunctionsAlgo;
import genlab.algog.gui.jfreechart.algos.AlgoGPlotAlgo;
import genlab.core.model.instance.IAlgoContainerInstance;
import genlab.core.model.instance.IAlgoInstance;
import genlab.core.model.instance.IGenlabWorkflowInstance;
import genlab.core.model.meta.AlgoCategory;
import genlab.core.model.meta.ExistingAlgoCategories;
import genlab.core.model.meta.IFlowType;
import genlab.core.model.meta.basics.algos.ConstantValueDouble;
import genlab.gui.examples.contributors.GenlabExampleDifficulty;
import genlab.gui.examples.contributors.IGenlabExample;
import genlab.gui.jfreechart.algos.ScatterPlotAlgo;
import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
public class ExampleTestFunctionChakongHaimes implements IGenlabExample {
public ExampleTestFunctionChakongHaimes() {
}
@Override
public void fillInstance(IGenlabWorkflowInstance workflow) {
// genetic algo host
final NSGA2GeneticExplorationAlgo nsgaAlgo = new NSGA2GeneticExplorationAlgo();
final IAlgoContainerInstance nsgaInstance = (IAlgoContainerInstance)nsgaAlgo.createInstance(workflow);
workflow.addAlgoInstance(nsgaInstance);
// genome
final GenomeAlgo genomeAlgo = new GenomeAlgo();
final IAlgoInstance genomeInstance = genomeAlgo.createInstance(workflow);
genomeInstance.setName("Chakong_Haimes");
nsgaInstance.addChildren(genomeInstance);
genomeInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(genomeInstance);
// genes
final DoubleGeneAlgo doubleGeneAlgo = new DoubleGeneAlgo();
final IAlgoInstance geneXInstance = doubleGeneAlgo.createInstance(workflow);
geneXInstance.setName("x");
nsgaInstance.addChildren(geneXInstance);
geneXInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneXInstance);
geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -20d);
- geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 100d);
+ geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 20d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneXInstance,
IntegerGeneAlgo.INPUT_GENOME
);
final IAlgoInstance geneYInstance = doubleGeneAlgo.createInstance(workflow);
geneYInstance.setName("y");
nsgaInstance.addChildren(geneYInstance);
geneYInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneYInstance);
- geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -100d);
+ geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -20d);
geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 20d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneYInstance,
IntegerGeneAlgo.INPUT_GENOME
);
// test function
final VerificationFunctionsAlgo verificationFunctionAlgo = new VerificationFunctionsAlgo();
final IAlgoInstance verificationFunctionInstance = verificationFunctionAlgo.createInstance(workflow);
verificationFunctionInstance.setName("verification function");
verificationFunctionInstance.setContainer(nsgaInstance);
verificationFunctionInstance.setValueForParameter(
VerificationFunctionsAlgo.PARAM_FUNCTION,
VerificationFunctionsAlgo.EAvailableFunctions.CHAKONG_HAIMES.ordinal()
);
nsgaInstance.addChildren(verificationFunctionInstance);
workflow.addAlgoInstance(verificationFunctionInstance);
workflow.connect(
geneXInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_X
);
workflow.connect(
geneYInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_Y
);
final GoalAlgo goalAlgo = new GoalAlgo();
final ConstantValueDouble constantDoubleAlgo = new ConstantValueDouble();
final IAlgoInstance constantDoubleZero = constantDoubleAlgo.createInstance(workflow);
constantDoubleZero.setContainer(nsgaInstance);
nsgaInstance.addChildren(constantDoubleZero);
workflow.addAlgoInstance(constantDoubleZero);
constantDoubleZero.setValueForParameter(constantDoubleAlgo.getConstantParameter(), -10000.0);
// set goal 1: f1
{
final IAlgoInstance goalF1 = goalAlgo.createInstance(workflow);
goalF1.setName("f1");
goalF1.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF1);
workflow.addAlgoInstance(goalF1);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F1,
goalF1, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF1, GoalAlgo.INPUT_TARGET
);
}
// set goal density
{
final IAlgoInstance goalF2 = goalAlgo.createInstance(workflow);
goalF2.setName("f2");
goalF2.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF2);
workflow.addAlgoInstance(goalF2);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F2,
goalF2, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF2, GoalAlgo.INPUT_TARGET
);
}
// add displays
{
final AlgoGPlotAlgo algogPlotAlgo = new AlgoGPlotAlgo();
final IAlgoInstance algogPlotInstance = algogPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algogPlotInstance);
algogPlotInstance.setName("exploration of Pareto");
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algogPlotInstance,
AlgoGPlotAlgo.INPUT_TABLE
);
}
{
final ScatterPlotAlgo scatterPlotAlgo = new ScatterPlotAlgo();
final IAlgoInstance algoScatterPlotInstance = scatterPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algoScatterPlotInstance);
algoScatterPlotInstance.setName("Pareto fronts");
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_X, 6);
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_Y, 3);
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algoScatterPlotInstance,
ScatterPlotAlgo.INPUT_TABLE
);
}
}
@Override
public String getFileName() {
return "geneticalgo_multigoal_testfunction_chakong_haimes";
}
@Override
public String getName() {
return "test function Chakong Haimes for multi-objective genetic algorithms";
}
@Override
public String getDescription() {
return "applies NSGA2 on the Chakong Haimes test function with a display of the Pareto front; enables the checking of the NSGA 2 behaviour";
}
@Override
public void createFiles(File resourcesDirectory) {
}
@Override
public GenlabExampleDifficulty getDifficulty() {
return GenlabExampleDifficulty.MEDIUM;
}
@Override
public Collection<IFlowType<?>> getIllustratedFlowTypes() {
return Collections.EMPTY_LIST;
}
@Override
public Collection<AlgoCategory> getIllustratedAlgoCategories() {
return new LinkedList<AlgoCategory>() {{ add(ExistingAlgoCategories.EXPLORATION_GENETIC_ALGOS); }};
}
}
| false | true | public void fillInstance(IGenlabWorkflowInstance workflow) {
// genetic algo host
final NSGA2GeneticExplorationAlgo nsgaAlgo = new NSGA2GeneticExplorationAlgo();
final IAlgoContainerInstance nsgaInstance = (IAlgoContainerInstance)nsgaAlgo.createInstance(workflow);
workflow.addAlgoInstance(nsgaInstance);
// genome
final GenomeAlgo genomeAlgo = new GenomeAlgo();
final IAlgoInstance genomeInstance = genomeAlgo.createInstance(workflow);
genomeInstance.setName("Chakong_Haimes");
nsgaInstance.addChildren(genomeInstance);
genomeInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(genomeInstance);
// genes
final DoubleGeneAlgo doubleGeneAlgo = new DoubleGeneAlgo();
final IAlgoInstance geneXInstance = doubleGeneAlgo.createInstance(workflow);
geneXInstance.setName("x");
nsgaInstance.addChildren(geneXInstance);
geneXInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneXInstance);
geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -20d);
geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 100d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneXInstance,
IntegerGeneAlgo.INPUT_GENOME
);
final IAlgoInstance geneYInstance = doubleGeneAlgo.createInstance(workflow);
geneYInstance.setName("y");
nsgaInstance.addChildren(geneYInstance);
geneYInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneYInstance);
geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -100d);
geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 20d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneYInstance,
IntegerGeneAlgo.INPUT_GENOME
);
// test function
final VerificationFunctionsAlgo verificationFunctionAlgo = new VerificationFunctionsAlgo();
final IAlgoInstance verificationFunctionInstance = verificationFunctionAlgo.createInstance(workflow);
verificationFunctionInstance.setName("verification function");
verificationFunctionInstance.setContainer(nsgaInstance);
verificationFunctionInstance.setValueForParameter(
VerificationFunctionsAlgo.PARAM_FUNCTION,
VerificationFunctionsAlgo.EAvailableFunctions.CHAKONG_HAIMES.ordinal()
);
nsgaInstance.addChildren(verificationFunctionInstance);
workflow.addAlgoInstance(verificationFunctionInstance);
workflow.connect(
geneXInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_X
);
workflow.connect(
geneYInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_Y
);
final GoalAlgo goalAlgo = new GoalAlgo();
final ConstantValueDouble constantDoubleAlgo = new ConstantValueDouble();
final IAlgoInstance constantDoubleZero = constantDoubleAlgo.createInstance(workflow);
constantDoubleZero.setContainer(nsgaInstance);
nsgaInstance.addChildren(constantDoubleZero);
workflow.addAlgoInstance(constantDoubleZero);
constantDoubleZero.setValueForParameter(constantDoubleAlgo.getConstantParameter(), -10000.0);
// set goal 1: f1
{
final IAlgoInstance goalF1 = goalAlgo.createInstance(workflow);
goalF1.setName("f1");
goalF1.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF1);
workflow.addAlgoInstance(goalF1);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F1,
goalF1, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF1, GoalAlgo.INPUT_TARGET
);
}
// set goal density
{
final IAlgoInstance goalF2 = goalAlgo.createInstance(workflow);
goalF2.setName("f2");
goalF2.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF2);
workflow.addAlgoInstance(goalF2);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F2,
goalF2, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF2, GoalAlgo.INPUT_TARGET
);
}
// add displays
{
final AlgoGPlotAlgo algogPlotAlgo = new AlgoGPlotAlgo();
final IAlgoInstance algogPlotInstance = algogPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algogPlotInstance);
algogPlotInstance.setName("exploration of Pareto");
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algogPlotInstance,
AlgoGPlotAlgo.INPUT_TABLE
);
}
{
final ScatterPlotAlgo scatterPlotAlgo = new ScatterPlotAlgo();
final IAlgoInstance algoScatterPlotInstance = scatterPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algoScatterPlotInstance);
algoScatterPlotInstance.setName("Pareto fronts");
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_X, 6);
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_Y, 3);
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algoScatterPlotInstance,
ScatterPlotAlgo.INPUT_TABLE
);
}
}
| public void fillInstance(IGenlabWorkflowInstance workflow) {
// genetic algo host
final NSGA2GeneticExplorationAlgo nsgaAlgo = new NSGA2GeneticExplorationAlgo();
final IAlgoContainerInstance nsgaInstance = (IAlgoContainerInstance)nsgaAlgo.createInstance(workflow);
workflow.addAlgoInstance(nsgaInstance);
// genome
final GenomeAlgo genomeAlgo = new GenomeAlgo();
final IAlgoInstance genomeInstance = genomeAlgo.createInstance(workflow);
genomeInstance.setName("Chakong_Haimes");
nsgaInstance.addChildren(genomeInstance);
genomeInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(genomeInstance);
// genes
final DoubleGeneAlgo doubleGeneAlgo = new DoubleGeneAlgo();
final IAlgoInstance geneXInstance = doubleGeneAlgo.createInstance(workflow);
geneXInstance.setName("x");
nsgaInstance.addChildren(geneXInstance);
geneXInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneXInstance);
geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -20d);
geneXInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 20d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneXInstance,
IntegerGeneAlgo.INPUT_GENOME
);
final IAlgoInstance geneYInstance = doubleGeneAlgo.createInstance(workflow);
geneYInstance.setName("y");
nsgaInstance.addChildren(geneYInstance);
geneYInstance.setContainer(nsgaInstance);
workflow.addAlgoInstance(geneYInstance);
geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MINIMUM, -20d);
geneYInstance.setValueForParameter(DoubleGeneAlgo.PARAM_MAXIMUM, 20d);
workflow.connect(
genomeInstance,
GenomeAlgo.OUTPUT_GENOME,
geneYInstance,
IntegerGeneAlgo.INPUT_GENOME
);
// test function
final VerificationFunctionsAlgo verificationFunctionAlgo = new VerificationFunctionsAlgo();
final IAlgoInstance verificationFunctionInstance = verificationFunctionAlgo.createInstance(workflow);
verificationFunctionInstance.setName("verification function");
verificationFunctionInstance.setContainer(nsgaInstance);
verificationFunctionInstance.setValueForParameter(
VerificationFunctionsAlgo.PARAM_FUNCTION,
VerificationFunctionsAlgo.EAvailableFunctions.CHAKONG_HAIMES.ordinal()
);
nsgaInstance.addChildren(verificationFunctionInstance);
workflow.addAlgoInstance(verificationFunctionInstance);
workflow.connect(
geneXInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_X
);
workflow.connect(
geneYInstance,
DoubleGeneAlgo.OUTPUT_VALUE,
verificationFunctionInstance,
VerificationFunctionsAlgo.INPUT_Y
);
final GoalAlgo goalAlgo = new GoalAlgo();
final ConstantValueDouble constantDoubleAlgo = new ConstantValueDouble();
final IAlgoInstance constantDoubleZero = constantDoubleAlgo.createInstance(workflow);
constantDoubleZero.setContainer(nsgaInstance);
nsgaInstance.addChildren(constantDoubleZero);
workflow.addAlgoInstance(constantDoubleZero);
constantDoubleZero.setValueForParameter(constantDoubleAlgo.getConstantParameter(), -10000.0);
// set goal 1: f1
{
final IAlgoInstance goalF1 = goalAlgo.createInstance(workflow);
goalF1.setName("f1");
goalF1.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF1);
workflow.addAlgoInstance(goalF1);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F1,
goalF1, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF1, GoalAlgo.INPUT_TARGET
);
}
// set goal density
{
final IAlgoInstance goalF2 = goalAlgo.createInstance(workflow);
goalF2.setName("f2");
goalF2.setContainer(nsgaInstance);
nsgaInstance.addChildren(goalF2);
workflow.addAlgoInstance(goalF2);
workflow.connect(
verificationFunctionInstance, VerificationFunctionsAlgo.OUTPUT_F2,
goalF2, GoalAlgo.INPUT_VALUE
);
workflow.connect(
constantDoubleZero, ConstantValueDouble.OUTPUT,
goalF2, GoalAlgo.INPUT_TARGET
);
}
// add displays
{
final AlgoGPlotAlgo algogPlotAlgo = new AlgoGPlotAlgo();
final IAlgoInstance algogPlotInstance = algogPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algogPlotInstance);
algogPlotInstance.setName("exploration of Pareto");
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algogPlotInstance,
AlgoGPlotAlgo.INPUT_TABLE
);
}
{
final ScatterPlotAlgo scatterPlotAlgo = new ScatterPlotAlgo();
final IAlgoInstance algoScatterPlotInstance = scatterPlotAlgo.createInstance(workflow);
workflow.addAlgoInstance(algoScatterPlotInstance);
algoScatterPlotInstance.setName("Pareto fronts");
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_X, 6);
algoScatterPlotInstance.setValueForParameter(ScatterPlotAlgo.PARAM_COLUMN_Y, 3);
workflow.connect(
nsgaInstance,
NSGA2GeneticExplorationAlgo.OUTPUT_TABLE_PARETO,
algoScatterPlotInstance,
ScatterPlotAlgo.INPUT_TABLE
);
}
}
|
diff --git a/src/main/java/com/mojang/minecraft/mob/HumanoidMob.java b/src/main/java/com/mojang/minecraft/mob/HumanoidMob.java
index 9bd3742..e0c2753 100644
--- a/src/main/java/com/mojang/minecraft/mob/HumanoidMob.java
+++ b/src/main/java/com/mojang/minecraft/mob/HumanoidMob.java
@@ -1,134 +1,134 @@
package com.mojang.minecraft.mob;
import com.mojang.minecraft.level.Level;
import com.mojang.minecraft.level.tile.Block;
import com.mojang.minecraft.level.tile.BlockModelRenderer;
import com.mojang.minecraft.model.AnimalModel;
import com.mojang.minecraft.model.HumanoidModel;
import com.mojang.minecraft.model.Model;
import com.mojang.minecraft.render.ShapeRenderer;
import com.mojang.minecraft.render.TextureManager;
import org.lwjgl.opengl.GL11;
public class HumanoidMob extends Mob {
public static final long serialVersionUID = 0L;
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public boolean helmet = Math.random() < 0.20000000298023224D;
public boolean armor = Math.random() < 0.20000000298023224D;
BlockModelRenderer block;
public HumanoidMob(Level var1, float var2, float var3, float var4) {
super(var1);
this.modelName = "humanoid";
this.setPos(var2, var3, var4);
}
public void renderModel(TextureManager var1, float var2, float var3, float var4, float var5,
float var6, float var7) {
if (this.modelName == "sheep") {
renderSheep(var1, var2, var3, var4, var5, var6, var7);
return;
} else if (isInteger(this.modelName)) {
try {
if (block == null) {
block = new BlockModelRenderer(
Block.blocks[Integer.parseInt(this.modelName)].textureId);
}
GL11.glPushMatrix();
GL11.glTranslatef(-0.5f, 0.4f, -0.5f);
GL11.glBindTexture(3553, var1.load("/terrain.png"));
block.renderPreview(ShapeRenderer.instance);
GL11.glPopMatrix();
} catch (Exception e) {
this.modelName = "humanoid";
}
return;
}
super.renderModel(var1, var2, var3, var4, var5, var6, var7);
Model model = modelCache.getModel(this.modelName);
GL11.glEnable(3008);
if (this.allowAlpha) {
GL11.glEnable(2884);
}
- if (this.hasHair) {
+ if (this.hasHair && model instanceof HumanoidModel) {
GL11.glDisable(2884);
HumanoidModel modelHeadwear = null;
(modelHeadwear = (HumanoidModel) model).headwear.yaw = modelHeadwear.head.yaw;
modelHeadwear.headwear.pitch = modelHeadwear.head.pitch;
modelHeadwear.headwear.render(var7);
GL11.glEnable(2884);
}
if (this.armor || this.helmet) {
GL11.glBindTexture(3553, var1.load("/armor/plate.png"));
GL11.glDisable(2884);
HumanoidModel modelArmour;
(modelArmour = (HumanoidModel) modelCache.getModel("humanoid.armor")).head.render = this.helmet;
modelArmour.body.render = this.armor;
modelArmour.rightArm.render = this.armor;
modelArmour.leftArm.render = this.armor;
modelArmour.rightLeg.render = false;
modelArmour.leftLeg.render = false;
HumanoidModel var11 = (HumanoidModel) model;
modelArmour.head.yaw = var11.head.yaw;
modelArmour.head.pitch = var11.head.pitch;
modelArmour.rightArm.pitch = var11.rightArm.pitch;
modelArmour.rightArm.roll = var11.rightArm.roll;
modelArmour.leftArm.pitch = var11.leftArm.pitch;
modelArmour.leftArm.roll = var11.leftArm.roll;
modelArmour.rightLeg.pitch = var11.rightLeg.pitch;
modelArmour.leftLeg.pitch = var11.leftLeg.pitch;
modelArmour.head.render(var7);
modelArmour.body.render(var7);
modelArmour.rightArm.render(var7);
modelArmour.leftArm.render(var7);
modelArmour.rightLeg.render(var7);
modelArmour.leftLeg.render(var7);
GL11.glEnable(2884);
}
GL11.glDisable(3008);
}
public void renderSheep(TextureManager var1, float var2, float var3, float var4, float var5,
float var6, float var7) {
AnimalModel var8;
float var9 = (var8 = (AnimalModel) modelCache.getModel("sheep")).head.y;
float var10 = var8.head.z;
super.renderModel(var1, var2, var3, var4, var5, var6, var7);
GL11.glBindTexture(3553, var1.load("/mob/sheep_fur.png"));
AnimalModel var11;
(var11 = (AnimalModel) modelCache.getModel("sheep.fur")).head.yaw = var8.head.yaw;
var11.head.pitch = var8.head.pitch;
var11.head.y = var8.head.y;
var11.head.x = var8.head.x;
var11.body.yaw = var8.body.yaw;
var11.body.pitch = var8.body.pitch;
var11.leg1.pitch = var8.leg1.pitch;
var11.leg2.pitch = var8.leg2.pitch;
var11.leg3.pitch = var8.leg3.pitch;
var11.leg4.pitch = var8.leg4.pitch;
var11.head.render(var7);
var11.body.render(var7);
var11.leg1.render(var7);
var11.leg2.render(var7);
var11.leg3.render(var7);
var11.leg4.render(var7);
var8.head.y = var9;
var8.head.z = var10;
}
}
| true | true | public void renderModel(TextureManager var1, float var2, float var3, float var4, float var5,
float var6, float var7) {
if (this.modelName == "sheep") {
renderSheep(var1, var2, var3, var4, var5, var6, var7);
return;
} else if (isInteger(this.modelName)) {
try {
if (block == null) {
block = new BlockModelRenderer(
Block.blocks[Integer.parseInt(this.modelName)].textureId);
}
GL11.glPushMatrix();
GL11.glTranslatef(-0.5f, 0.4f, -0.5f);
GL11.glBindTexture(3553, var1.load("/terrain.png"));
block.renderPreview(ShapeRenderer.instance);
GL11.glPopMatrix();
} catch (Exception e) {
this.modelName = "humanoid";
}
return;
}
super.renderModel(var1, var2, var3, var4, var5, var6, var7);
Model model = modelCache.getModel(this.modelName);
GL11.glEnable(3008);
if (this.allowAlpha) {
GL11.glEnable(2884);
}
if (this.hasHair) {
GL11.glDisable(2884);
HumanoidModel modelHeadwear = null;
(modelHeadwear = (HumanoidModel) model).headwear.yaw = modelHeadwear.head.yaw;
modelHeadwear.headwear.pitch = modelHeadwear.head.pitch;
modelHeadwear.headwear.render(var7);
GL11.glEnable(2884);
}
if (this.armor || this.helmet) {
GL11.glBindTexture(3553, var1.load("/armor/plate.png"));
GL11.glDisable(2884);
HumanoidModel modelArmour;
(modelArmour = (HumanoidModel) modelCache.getModel("humanoid.armor")).head.render = this.helmet;
modelArmour.body.render = this.armor;
modelArmour.rightArm.render = this.armor;
modelArmour.leftArm.render = this.armor;
modelArmour.rightLeg.render = false;
modelArmour.leftLeg.render = false;
HumanoidModel var11 = (HumanoidModel) model;
modelArmour.head.yaw = var11.head.yaw;
modelArmour.head.pitch = var11.head.pitch;
modelArmour.rightArm.pitch = var11.rightArm.pitch;
modelArmour.rightArm.roll = var11.rightArm.roll;
modelArmour.leftArm.pitch = var11.leftArm.pitch;
modelArmour.leftArm.roll = var11.leftArm.roll;
modelArmour.rightLeg.pitch = var11.rightLeg.pitch;
modelArmour.leftLeg.pitch = var11.leftLeg.pitch;
modelArmour.head.render(var7);
modelArmour.body.render(var7);
modelArmour.rightArm.render(var7);
modelArmour.leftArm.render(var7);
modelArmour.rightLeg.render(var7);
modelArmour.leftLeg.render(var7);
GL11.glEnable(2884);
}
GL11.glDisable(3008);
}
| public void renderModel(TextureManager var1, float var2, float var3, float var4, float var5,
float var6, float var7) {
if (this.modelName == "sheep") {
renderSheep(var1, var2, var3, var4, var5, var6, var7);
return;
} else if (isInteger(this.modelName)) {
try {
if (block == null) {
block = new BlockModelRenderer(
Block.blocks[Integer.parseInt(this.modelName)].textureId);
}
GL11.glPushMatrix();
GL11.glTranslatef(-0.5f, 0.4f, -0.5f);
GL11.glBindTexture(3553, var1.load("/terrain.png"));
block.renderPreview(ShapeRenderer.instance);
GL11.glPopMatrix();
} catch (Exception e) {
this.modelName = "humanoid";
}
return;
}
super.renderModel(var1, var2, var3, var4, var5, var6, var7);
Model model = modelCache.getModel(this.modelName);
GL11.glEnable(3008);
if (this.allowAlpha) {
GL11.glEnable(2884);
}
if (this.hasHair && model instanceof HumanoidModel) {
GL11.glDisable(2884);
HumanoidModel modelHeadwear = null;
(modelHeadwear = (HumanoidModel) model).headwear.yaw = modelHeadwear.head.yaw;
modelHeadwear.headwear.pitch = modelHeadwear.head.pitch;
modelHeadwear.headwear.render(var7);
GL11.glEnable(2884);
}
if (this.armor || this.helmet) {
GL11.glBindTexture(3553, var1.load("/armor/plate.png"));
GL11.glDisable(2884);
HumanoidModel modelArmour;
(modelArmour = (HumanoidModel) modelCache.getModel("humanoid.armor")).head.render = this.helmet;
modelArmour.body.render = this.armor;
modelArmour.rightArm.render = this.armor;
modelArmour.leftArm.render = this.armor;
modelArmour.rightLeg.render = false;
modelArmour.leftLeg.render = false;
HumanoidModel var11 = (HumanoidModel) model;
modelArmour.head.yaw = var11.head.yaw;
modelArmour.head.pitch = var11.head.pitch;
modelArmour.rightArm.pitch = var11.rightArm.pitch;
modelArmour.rightArm.roll = var11.rightArm.roll;
modelArmour.leftArm.pitch = var11.leftArm.pitch;
modelArmour.leftArm.roll = var11.leftArm.roll;
modelArmour.rightLeg.pitch = var11.rightLeg.pitch;
modelArmour.leftLeg.pitch = var11.leftLeg.pitch;
modelArmour.head.render(var7);
modelArmour.body.render(var7);
modelArmour.rightArm.render(var7);
modelArmour.leftArm.render(var7);
modelArmour.rightLeg.render(var7);
modelArmour.leftLeg.render(var7);
GL11.glEnable(2884);
}
GL11.glDisable(3008);
}
|
diff --git a/libraries/BridJ/src/main/java/org/bridj/Platform.java b/libraries/BridJ/src/main/java/org/bridj/Platform.java
index a301b3b7..7e13264e 100644
--- a/libraries/BridJ/src/main/java/org/bridj/Platform.java
+++ b/libraries/BridJ/src/main/java/org/bridj/Platform.java
@@ -1,639 +1,639 @@
package org.bridj;
import org.bridj.util.ProcessUtils;
import java.util.Set;
import java.util.HashSet;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Collections;
import java.util.Collection;
import java.util.ArrayList;
import java.net.MalformedURLException;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.logging.Level;
import org.bridj.util.StringUtils;
/**
* Information about the execution platform (OS, architecture, native sizes...) and platform-specific actions.
* <ul>
* <li>To know if the JVM platform is 32 bits or 64 bits, use {@link Platform#is64Bits()}
* </li><li>To know if the OS is an Unix-like system, use {@link Platform#isUnix()}
* </li><li>To open files and URLs in a platform-specific way, use {@link Platform#open(File)}, {@link Platform#open(URL)}, {@link Platform#show(File)}
* </li></ul>
* @author ochafik
*/
public class Platform {
static final String osName = System.getProperty("os.name", "");
private static boolean inited;
static final String BridJLibraryName = "bridj";
public static final int
POINTER_SIZE,
WCHAR_T_SIZE,
SIZE_T_SIZE,
TIME_T_SIZE,
CLONG_SIZE;
/*interface FunInt {
int apply();
}
static int tryInt(FunInt f, int defaultValue) {
try {
return f.apply();
} catch (Throwable th) {
return defaultValue;
}
}*/
static final ClassLoader systemClassLoader;
public static ClassLoader getClassLoader() {
return getClassLoader(BridJ.class);
}
public static ClassLoader getClassLoader(Class<?> cl) {
ClassLoader loader = cl == null ? null : cl.getClassLoader();
return loader == null ? systemClassLoader : loader;
}
/*
public static class utsname {
public final String sysname, nodename, release, version, machine;
public utsname(String sysname, String nodename, String release, String version, String machine) {
this.sysname = sysname;
this.nodename = nodename;
this.release = release;
this.version = version;
this.machine = machine;
}
public String toString() {
StringBuilder b = new StringBuilder("{\n");
b.append("\tsysname: \"").append(sysname).append("\",\n");
b.append("\tnodename: \"").append(nodename).append("\",\n");
b.append("\trelease: \"").append(release).append("\",\n");
b.append("\tversion: \"").append(version).append("\",\n");
b.append("\tmachine: \"").append(machine).append("\"\n");
return b.append("}").toString();
}
}
public static native utsname uname();
*/
static final List<String> embeddedLibraryResourceRoots = new ArrayList<String>();
/**
* BridJ is able to automatically extract native binaries bundled in the application's JARs, using a customizable root path and a predefined architecture-dependent subpath. This method adds an alternative root path to the search list.<br>
* For instance, if you want to load library "mylib" and call <code>addEmbeddedLibraryResourceRoot("my/company/lib/")</code>, BridJ will look for library in the following locations :
* <ul>
* <li>"my/company/lib/darwin_universal/libmylib.dylib" on MacOS X (or darwin_x86, darwin_x64, darwin_ppc if the binary is not universal)</li>
* <li>"my/company/lib/win32/mylib.dll" on Windows (use win64 on 64 bits architectures)</li>
* <li>"my/company/lib/linux_x86/libmylib.so" on Linux (use linux_x64 on 64 bits architectures)</li>
* <li>"my/company/lib/sunos_x86/libmylib.so" on Solaris (use sunos_x64 / sunos_sparc on other architectures)</li>
* <li>"lib/armeabi/libmylib.so" on Android (for Android-specific reasons, only the "lib" sub-path can effectively contain loadable binaries)</li>
* </ul>
* For other platforms or for an updated list of supported platforms, please have a look at BridJ's JAR contents (under "org/bridj/lib") and/or to its source tree, browsable online.
*/
public static synchronized void addEmbeddedLibraryResourceRoot(String root) {
embeddedLibraryResourceRoots.add(0, root);
}
static Set<File> temporaryExtractedLibraryCanonicalFiles = Collections.synchronizedSet(new LinkedHashSet<File>());
static void addTemporaryExtractedLibraryFileToDeleteOnExit(File file) throws IOException {
File canonicalFile = file.getCanonicalFile();
// Give a chance to NativeLibrary.release() to delete the file :
temporaryExtractedLibraryCanonicalFiles.add(canonicalFile);
// Ask Java to delete the file upon exit if it still exists
canonicalFile.deleteOnExit();
}
private static final String arch;
private static boolean is64Bits;
static {
arch = System.getProperty("os.arch");
{
String dataModel = System.getProperty("sun.arch.data.model", System.getProperty("com.ibm.vm.bitmode"));
if ("32".equals(dataModel))
is64Bits = false;
else if ("64".equals(dataModel))
is64Bits = true;
else {
is64Bits =
arch.contains("64") ||
arch.equalsIgnoreCase("sparcv9");
}
}
systemClassLoader = createClassLoader();
addEmbeddedLibraryResourceRoot("lib/");
if (!isAndroid()) {
addEmbeddedLibraryResourceRoot("org/bridj/lib/");
if (!Version.VERSION_SPECIFIC_SUB_PACKAGE.equals(""))
addEmbeddedLibraryResourceRoot("org/bridj/" + Version.VERSION_SPECIFIC_SUB_PACKAGE + "/lib/");
}
try {
initLibrary();
} catch (Throwable th) {
th.printStackTrace();
}
POINTER_SIZE = sizeOf_ptrdiff_t();
WCHAR_T_SIZE = sizeOf_wchar_t();
SIZE_T_SIZE = sizeOf_size_t();
TIME_T_SIZE = sizeOf_time_t();
CLONG_SIZE = sizeOf_long();
is64Bits = POINTER_SIZE == 8;
Runtime.getRuntime().addShutdownHook(new Thread() { public void run() {
shutdown();
}});
}
private static List<NativeLibrary> nativeLibraries = new ArrayList<NativeLibrary>();
static void addNativeLibrary(NativeLibrary library) {
synchronized (nativeLibraries) {
nativeLibraries.add(library);
}
}
private static void shutdown() {
//releaseNativeLibraries();
deleteTemporaryExtractedLibraryFiles();
}
private static void releaseNativeLibraries() {
synchronized (nativeLibraries) {
// Release libraries in reverse order :
for (int iLibrary = nativeLibraries.size(); iLibrary-- != 0;) {
NativeLibrary lib = nativeLibraries.get(iLibrary);
try {
lib.release();
} catch (Throwable th) {
BridJ.log(Level.SEVERE, "Failed to release library '" + lib.path + "' : " + th, th);
}
}
}
}
private static void deleteTemporaryExtractedLibraryFiles() {
synchronized (temporaryExtractedLibraryCanonicalFiles) {
// Release libraries in reverse order :
List<File> filesToDeleteAfterExit = new ArrayList<File>();
for (File tempFile : Platform.temporaryExtractedLibraryCanonicalFiles) {
if (tempFile.delete()) {
if (BridJ.verbose)
BridJ.log(Level.INFO, "Deleted temporary library file '" + tempFile + "'");
} else
filesToDeleteAfterExit.add(tempFile);
}
if (!filesToDeleteAfterExit.isEmpty()) {
if (BridJ.verbose)
BridJ.log(Level.INFO, "Attempting to delete " + filesToDeleteAfterExit.size() + " files after JVM exit : " + StringUtils.implode(filesToDeleteAfterExit, ", "));
try {
ProcessUtils.startJavaProcess(DeleteFiles.class, filesToDeleteAfterExit);
} catch (Throwable ex) {
BridJ.log(Level.SEVERE, "Failed to launch process to delete files after JVM exit : " + ex, ex);
}
}
}
}
public static class DeleteFiles {
static boolean delete(List<File> files) {
for (Iterator<File> it = files.iterator(); it.hasNext();) {
File file = it.next();
if (file.delete())
it.remove();
}
return files.isEmpty();
}
final static long
TRY_DELETE_EVERY_MILLIS = 50,
FAIL_AFTER_MILLIS = 10000;
public static void main(String[] args) {
try {
List<File> files = new LinkedList<File>();
for (String arg : args)
files.add(new File(arg));
long start = System.currentTimeMillis();
while (!delete(files)) {
long elapsed = System.currentTimeMillis() - start;
if (elapsed > FAIL_AFTER_MILLIS) {
System.err.println("Failed to delete the following files : " + StringUtils.implode(files));
System.exit(1);
}
Thread.sleep(TRY_DELETE_EVERY_MILLIS);
}
} catch (Throwable th) {
th.printStackTrace();
} finally {
System.exit(0);
}
}
}
static ClassLoader createClassLoader()
{
List<URL> urls = new ArrayList<URL>();
for (String propName : new String[] { "java.class.path", "sun.boot.class.path" }) {
String prop = System.getProperty(propName);
if (prop == null)
continue;
for (String path : prop.split(File.pathSeparator)) {
path = path.trim();
if (path.length() == 0)
continue;
URL url;
try {
url = new URL(path);
} catch (MalformedURLException ex) {
try {
url = new File(path).toURI().toURL();
} catch (MalformedURLException ex2) {
url = null;
}
}
if (url != null)
urls.add(url);
}
}
//System.out.println("URLs for synthetic class loader :");
//for (URL url : urls)
// System.out.println("\t" + url);
return new URLClassLoader(urls.toArray(new URL[urls.size()]));
}
static String getenvOrProperty(String envName, String javaName, String defaultValue) {
String value = System.getenv(envName);
if (value == null)
value = System.getProperty(javaName);
if (value == null)
value = defaultValue;
return value;
}
- public static void initLibrary() {
+ public static synchronized void initLibrary() {
if (inited) {
return;
}
+ inited = true;
try {
boolean loaded = false;
String forceLibFile = getenvOrProperty("BRIDJ_LIBRARY", "bridj.library", null);
String lib = null;
if (forceLibFile != null) {
try {
System.load(lib = forceLibFile);
loaded = true;
} catch (Throwable ex) {
BridJ.log(Level.SEVERE, "Failed to load forced library " + forceLibFile, ex);
}
}
if (!loaded) {
if (!Platform.isAndroid()) {
try {
File libFile = extractEmbeddedLibraryResource(BridJLibraryName);
if (libFile == null) {
throw new FileNotFoundException(BridJLibraryName);
}
BridJ.log(Level.INFO, "Loading library " + libFile);
System.load(lib = libFile.toString());
BridJ.setNativeLibraryFile(BridJLibraryName, libFile);
loaded = true;
} catch (IOException ex) {
BridJ.log(Level.SEVERE, "Failed to load '" + BridJLibraryName + "'", ex);
}
}
if (!loaded) {
System.loadLibrary("bridj");
}
}
BridJ.log(Level.INFO, "Loaded library " + lib);
init();
- inited = true;
//if (BridJ.protectedMode)
// BridJ.log(Level.INFO, "Protected mode enabled");
if (BridJ.logCalls) {
BridJ.log(Level.INFO, "Calls logs enabled");
}
} catch (Throwable ex) {
throw new RuntimeException("Failed to initialize " + BridJ.class.getSimpleName(), ex);
}
}
private static native void init();
public static boolean isLinux() {
return isUnix() && osName.toLowerCase().contains("linux");
}
public static boolean isMacOSX() {
return isUnix() && (osName.startsWith("Mac") || osName.startsWith("Darwin"));
}
public static boolean isSolaris() {
return isUnix() && (osName.startsWith("SunOS") || osName.startsWith("Solaris"));
}
public static boolean isBSD() {
return isUnix() && (osName.contains("BSD") || isMacOSX());
}
public static boolean isUnix() {
return File.separatorChar == '/';
}
public static boolean isWindows() {
return File.separatorChar == '\\';
}
public static boolean isWindows7() {
return osName.equals("Windows 7");
}
/**
* Whether to use Unicode versions of Windows APIs rather than ANSI versions (for functions that haven't been bound yet : has no effect on functions that have already been bound).<br>
* Some Windows APIs such as SendMessage have two versions :
* <ul>
* <li>one that uses single-byte character strings (SendMessageA, with 'A' for ANSI strings)</li>
* <li>one that uses unicode character strings (SendMessageW, with 'W' for Wide strings).</li>
* </ul>
* <br>
* In a C/C++ program, this behaviour is controlled by the UNICODE macro definition.<br>
* By default, BridJ will use the Unicode versions. Set this field to false, set the bridj.useUnicodeVersionOfWindowsAPIs property to "false" or the BRIDJ_USE_UNICODE_VERSION_OF_WINDOWS_APIS environment variable to "0" to use the ANSI string version instead.
*/
public static boolean useUnicodeVersionOfWindowsAPIs = !(
"false".equals(System.getProperty("bridj.useUnicodeVersionOfWindowsAPIs")) ||
"0".equals(System.getenv("BRIDJ_USE_UNICODE_VERSION_OF_WINDOWS_APIS"))
);
private static String getArch() {
return arch;
}
/**
* Machine (as returned by `uname -m`, except for i686 which is actually i386), adjusted to the JVM platform (32 or 64 bits)
*/
public static String getMachine() {
String arch = getArch();
if (arch.equals("amd64") || arch.equals("x86_64")) {
if (is64Bits())
return "x86_64";
else
return "i386"; // we are running a 32 bits JVM on a 64 bits platform
}
return arch;
}
public static boolean isAndroid() {
return "dalvik".equalsIgnoreCase(System.getProperty("java.vm.name")) && isLinux();
}
public static boolean isArm() {
String arch = getArch();
return "arm".equals(arch);
}
public static boolean isSparc() {
String arch = getArch();
return
"sparc".equals(arch) ||
"sparcv9".equals(arch);
}
public static boolean is64Bits() {
return is64Bits;
}
public static boolean isAmd64Arch() {
String arch = getArch();
return arch.equals("x86_64");
}
static synchronized Collection<String> getEmbeddedLibraryResource(String name) {
Collection<String> ret = new ArrayList<String>();
for (String root : embeddedLibraryResourceRoots) {
if (root == null)
continue;
if (isWindows())
ret.add(root + (is64Bits() ? "win64/" : "win32/") + name + ".dll");
else if (isMacOSX()) {
String suff = "/lib" + name + ".dylib";
if (isArm())
ret.add(root + "iphoneos_arm32_arm" + suff);
else {
String pref = root + "darwin_";
String univ = pref + "universal" + suff;
if (isAmd64Arch()) {
ret.add(univ);
ret.add(pref + "x64" + suff);
} else
ret.add(univ);
}
}
else {
String path = null;
if (isAndroid()) {
assert root.equals("lib/");
path = root + "armeabi/"; // Android SDK + NDK-style .so embedding = lib/armeabi/libTest.so
}
else if (isLinux())
path = root + (is64Bits() ? "linux_x64/" : "linux_x86/");
else if (isSolaris()) {
if (isSparc()) {
path = root + (is64Bits() ? "sunos_sparc64/" : "sunos_sparc/");
} else {
path = root + (is64Bits() ? "sunos_x64/" : "sunos_x86/");
}
}
if (path != null) {
ret.add(path + "lib" + name + ".so");
ret.add(path + name + ".so");
}
}
}
if (ret.isEmpty())
throw new RuntimeException("Platform not supported ! (os.name='" + osName + "', os.arch='" + System.getProperty("os.arch") + "')");
if (BridJ.verbose)
BridJ.log(Level.INFO, "Embedded paths for library " + name + " : " + ret);
return ret;
}
static void tryDeleteFilesInSameDirectory(final File legitFile, final Pattern fileNamePattern, long atLeastOlderThanMillis) {
final long maxModifiedDateForDeletion = System.currentTimeMillis() - atLeastOlderThanMillis;
new Thread(new Runnable() { public void run() {
File dir = legitFile.getParentFile();
String legitFileName = legitFile.getName();
try {
for (String name : dir.list()) {
if (name.equals(legitFileName))
continue;
if (!fileNamePattern.matcher(name).matches())
continue;
File file = new File(dir, name);
if (file.lastModified() > maxModifiedDateForDeletion)
continue;
if (file.delete() && BridJ.verbose)
BridJ.log(Level.INFO, "Deleted old binary file '" + file + "'");
}
} catch (SecurityException ex) {
// no right to delete files in that directory
BridJ.log(Level.WARNING, "Failed to delete files matching '" + fileNamePattern + "' in directory '" + dir + "'", ex);
} catch (Throwable ex) {
BridJ.log(Level.SEVERE, "Unexpected error : " + ex, ex);
}
}}).start();
}
static final long DELETE_OLD_BINARIES_AFTER_MILLIS = 24 * 60 * 60 * 1000; // 24 hours
static File extractEmbeddedLibraryResource(String name) throws IOException {
String firstLibraryResource = null;
for (String libraryResource : getEmbeddedLibraryResource(name)) {
if (firstLibraryResource == null)
firstLibraryResource = libraryResource;
int i = libraryResource.lastIndexOf('.');
String ext = i < 0 ? "" : libraryResource.substring(i);
int len;
byte[] b = new byte[8196];
InputStream in = getClassLoader().getResourceAsStream(libraryResource);
if (in == null) {
File f = new File(libraryResource);
if (!f.exists())
f = new File(f.getName());
if (f.exists())
return f.getCanonicalFile();
//f = BridJ.getNativeLibraryFile(name);
// if (f.exists())
// return f.getCanonicalFile();
continue;
}
String fileName = new File(libraryResource).getName();
File libFile = File.createTempFile(fileName, ext);
if (BridJ.Switch.DeleteOldBinaries.enabled)
tryDeleteFilesInSameDirectory(libFile, Pattern.compile(Pattern.quote(fileName) + ".*?" + Pattern.quote(ext)), DELETE_OLD_BINARIES_AFTER_MILLIS);
OutputStream out = new BufferedOutputStream(new FileOutputStream(libFile));
while ((len = in.read(b)) > 0)
out.write(b, 0, len);
out.close();
in.close();
addTemporaryExtractedLibraryFileToDeleteOnExit(libFile);
return libFile;
}
return null;
//throw new FileNotFoundException(firstLibraryResource);
}
/**
* Opens an URL with the default system action.
* @param url url to open
* @throws NoSuchMethodException if opening an URL on the current platform is not supported
*/
public static final void open(URL url) throws NoSuchMethodException {
if (url.getProtocol().equals("file")) {
open(new File(url.getFile()));
} else {
if (Platform.isMacOSX()) {
execArgs("open", url.toString());
} else if (Platform.isWindows()) {
execArgs("rundll32", "url.dll,FileProtocolHandler", url.toString());
} else if (Platform.isUnix() && hasUnixCommand("gnome-open")) {
execArgs("gnome-open", url.toString());
} else if (Platform.isUnix() && hasUnixCommand("konqueror")) {
execArgs("konqueror", url.toString());
} else if (Platform.isUnix() && hasUnixCommand("mozilla")) {
execArgs("mozilla", url.toString());
} else {
throw new NoSuchMethodException("Cannot open urls on this platform");
}
}
}
/**
* Opens a file with the default system action.
* @param file file to open
* @throws NoSuchMethodException if opening a file on the current platform is not supported
*/
public static final void open(File file) throws NoSuchMethodException {
if (Platform.isMacOSX()) {
execArgs("open", file.getAbsolutePath());
} else if (Platform.isWindows()) {
if (file.isDirectory()) {
execArgs("explorer", file.getAbsolutePath());
} else {
execArgs("start", file.getAbsolutePath());
}
}
if (Platform.isUnix() && hasUnixCommand("gnome-open")) {
execArgs("gnome-open", file.toString());
} else if (Platform.isUnix() && hasUnixCommand("konqueror")) {
execArgs("konqueror", file.toString());
} else if (Platform.isSolaris() && file.isDirectory()) {
execArgs("/usr/dt/bin/dtfile", "-folder", file.getAbsolutePath());
} else {
throw new NoSuchMethodException("Cannot open files on this platform");
}
}
/**
* Show a file in its parent directory, if possible selecting the file (not possible on all platforms).
* @param file file to show in the system's default file navigator
* @throws NoSuchMethodException if showing a file on the current platform is not supported
*/
public static final void show(File file) throws NoSuchMethodException, IOException {
if (Platform.isWindows()) {
exec("explorer /e,/select,\"" + file.getCanonicalPath() + "\"");
} else {
open(file.getAbsoluteFile().getParentFile());
}
}
static final void execArgs(String... cmd) throws NoSuchMethodException {
try {
Runtime.getRuntime().exec(cmd);
} catch (Exception ex) {
ex.printStackTrace();
throw new NoSuchMethodException(ex.toString());
}
}
static final void exec(String cmd) throws NoSuchMethodException {
try {
Runtime.getRuntime().exec(cmd).waitFor();
} catch (Exception ex) {
ex.printStackTrace();
throw new NoSuchMethodException(ex.toString());
}
}
static final boolean hasUnixCommand(String name) {
try {
Process p = Runtime.getRuntime().exec(new String[]{"which", name});
return p.waitFor() == 0;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
static native int sizeOf_size_t();
static native int sizeOf_time_t();
static native int sizeOf_wchar_t();
static native int sizeOf_ptrdiff_t();
static native int sizeOf_long();
static native int getMaxDirectMappingArgCount();
}
| false | true | public static void initLibrary() {
if (inited) {
return;
}
try {
boolean loaded = false;
String forceLibFile = getenvOrProperty("BRIDJ_LIBRARY", "bridj.library", null);
String lib = null;
if (forceLibFile != null) {
try {
System.load(lib = forceLibFile);
loaded = true;
} catch (Throwable ex) {
BridJ.log(Level.SEVERE, "Failed to load forced library " + forceLibFile, ex);
}
}
if (!loaded) {
if (!Platform.isAndroid()) {
try {
File libFile = extractEmbeddedLibraryResource(BridJLibraryName);
if (libFile == null) {
throw new FileNotFoundException(BridJLibraryName);
}
BridJ.log(Level.INFO, "Loading library " + libFile);
System.load(lib = libFile.toString());
BridJ.setNativeLibraryFile(BridJLibraryName, libFile);
loaded = true;
} catch (IOException ex) {
BridJ.log(Level.SEVERE, "Failed to load '" + BridJLibraryName + "'", ex);
}
}
if (!loaded) {
System.loadLibrary("bridj");
}
}
BridJ.log(Level.INFO, "Loaded library " + lib);
init();
inited = true;
//if (BridJ.protectedMode)
// BridJ.log(Level.INFO, "Protected mode enabled");
if (BridJ.logCalls) {
BridJ.log(Level.INFO, "Calls logs enabled");
}
} catch (Throwable ex) {
throw new RuntimeException("Failed to initialize " + BridJ.class.getSimpleName(), ex);
}
}
| public static synchronized void initLibrary() {
if (inited) {
return;
}
inited = true;
try {
boolean loaded = false;
String forceLibFile = getenvOrProperty("BRIDJ_LIBRARY", "bridj.library", null);
String lib = null;
if (forceLibFile != null) {
try {
System.load(lib = forceLibFile);
loaded = true;
} catch (Throwable ex) {
BridJ.log(Level.SEVERE, "Failed to load forced library " + forceLibFile, ex);
}
}
if (!loaded) {
if (!Platform.isAndroid()) {
try {
File libFile = extractEmbeddedLibraryResource(BridJLibraryName);
if (libFile == null) {
throw new FileNotFoundException(BridJLibraryName);
}
BridJ.log(Level.INFO, "Loading library " + libFile);
System.load(lib = libFile.toString());
BridJ.setNativeLibraryFile(BridJLibraryName, libFile);
loaded = true;
} catch (IOException ex) {
BridJ.log(Level.SEVERE, "Failed to load '" + BridJLibraryName + "'", ex);
}
}
if (!loaded) {
System.loadLibrary("bridj");
}
}
BridJ.log(Level.INFO, "Loaded library " + lib);
init();
//if (BridJ.protectedMode)
// BridJ.log(Level.INFO, "Protected mode enabled");
if (BridJ.logCalls) {
BridJ.log(Level.INFO, "Calls logs enabled");
}
} catch (Throwable ex) {
throw new RuntimeException("Failed to initialize " + BridJ.class.getSimpleName(), ex);
}
}
|
diff --git a/src/qs/swornshop/Main.java b/src/qs/swornshop/Main.java
index 9bba868..f05b3dd 100644
--- a/src/qs/swornshop/Main.java
+++ b/src/qs/swornshop/Main.java
@@ -1,783 +1,783 @@
package qs.swornshop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Logger;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import qs.swornshop.notification.Claimable;
import qs.swornshop.notification.Notification;
import qs.swornshop.notification.Request;
import qs.swornshop.notification.SellRequest;
public class Main extends JavaPlugin implements Listener {
// TODO: Timed notifications
private static final int SIGN = 63;
public static Main instance;
public static Economy econ;
public static HashMap<String, Long> aliases = new HashMap<String, Long>();
public static HashMap<Long, String> itemNames = new HashMap<Long, String>();
protected HashMap<Location, Shop> shops = new HashMap<Location, Shop>();
protected HashMap<Player, ShopSelection> selectedShops = new HashMap<Player, ShopSelection>();
protected HashMap<String, ArrayDeque<Notification>> pending = new HashMap<String, ArrayDeque<Notification>>();
protected Logger log;
public Main() {}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(this, this);
instance = this;
log = this.getLogger();
loadItemNames();
loadAliases();
if (!economySetup()) {
log.warning("Could not set up server economy! Is Vault installed?");
throw new Error("Vault setup failed");
}
System.out.println(aliases.get("wood"));
}
@Override
public void onDisable() {}
@Override
public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
return true;
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
Help.showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("mk")) {
if (args.length < 2) {
sendError(pl, Help.create.toUsageString());
return true;
}
- if (!sender.hasPermission("shops.admin")) {
+ if (!sender.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
} else if (action.equalsIgnoreCase("add") ||
action.equalsIgnoreCase("+") ||
action.equalsIgnoreCase("ad")) {
if (args.length < 2) {
sendError(pl, Help.add.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
- if (!selection.isOwner && !pl.hasPermission("shops.admin")) {
+ if (!selection.isOwner && !pl.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot add items to this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[1])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.add.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[2])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.add.toUsageString());
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wisth to add to this shop");
return true;
}
if (selection.shop.containsItem(stack)) {
sendError(pl, "That item has already been added to this shop");
sendError(pl, "Use /shop restock to restock");
return true;
}
ShopEntry newEntry = new ShopEntry();
newEntry.setItem(stack);
newEntry.retailPrice = retailAmount;
newEntry.refundPrice = refundAmount;
selection.shop.addEntry(newEntry);
pl.setItemInHand(null);
} else if ((action.equalsIgnoreCase("restock") ||
action.equalsIgnoreCase("r"))) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
- if (!selection.isOwner && !pl.hasPermission("shops.admin")) {
+ if (!selection.isOwner && !pl.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot restock this shop");
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to add to this shop");
return true;
}
ShopEntry entry = selection.shop.findEntry(stack);
if (entry == null) {
sendError(pl, "That item has not been added to this shop");
sendError(pl, "Use /shop add to add a new item");
return true;
}
entry.setAmount(entry.item.getAmount() + stack.getAmount());
pl.setItemInHand(null);
} else if (action.equalsIgnoreCase("set")) {
if (!selection.isOwner && !pl.hasPermission("shop.admin")) {
sendError(pl, "You cannot change this shop's prices");
return true;
}
if (args.length < 3) {
sendError(pl, Help.set.toUsageString());
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[2])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.set.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[3])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.set.toUsageString());
return true;
}
entry.retailPrice = retailAmount;
entry.refundPrice = refundAmount;
} else if (action.equalsIgnoreCase("buy") ||
action.equalsIgnoreCase("b")) {
if (args.length < 3) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
- if (selection.isOwner && !pl.hasPermission("shops.self")) {
+ if (selection.isOwner && !pl.hasPermission("swornshop.self")) {
sendError(pl, "You cannot buy items from this shop");
return true;
}
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (amount <= 0) {
sendError(pl, "You must buy a positive number of this item");
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
if (entry.item.getAmount() < amount) {
sendError(pl, "There are not enough of that item in the shop");
return true;
}
int max = entry.item.getMaxStackSize();
String itemName = getItemName(entry.item);
if (max > -1 && amount > max) {
sendError(pl, String.format("You may only buy §B%d %s§C at once", max, itemName));
return true;
}
if(!(econ.has(pl.getName(), amount * entry.retailPrice))){
sendError(pl, "You do not have sufficient funds");
return true;
}
ItemStack purchased = entry.item.clone();
purchased.setAmount(amount);
HashMap<Integer, ItemStack> overflow = pl.getInventory().addItem(purchased);
int refunded = 0;
if (overflow.size() > 0) {
refunded = overflow.get(0).getAmount();
if (overflow.size() == amount) {
sendError(pl, "You do not have any room in your inventory");
return true;
}
sender.sendMessage(String.format(
"Only §B%d %s§F fit in your inventory. You were charged §B$%.2f§F.",
amount - refunded, itemName, (amount - refunded) * entry.retailPrice));
} else {
sender.sendMessage(String.format(
"You bought §B%d %s§F for §B$%.2f§F.",
amount, itemName, amount * entry.retailPrice));
}
econ.withdrawPlayer(pl.getName(), (amount - refunded) * entry.retailPrice);
entry.item.setAmount(entry.item.getAmount() - (amount - refunded));
econ.depositPlayer(shop.owner, (amount - refunded) * entry.retailPrice);
} else if (action.equalsIgnoreCase("sell") ||
action.equalsIgnoreCase("s")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
- if (selection.isOwner && !pl.hasPermission("shops.self")) {
+ if (selection.isOwner && !pl.hasPermission("swornshop.self")) {
sendError(pl, "You cannot sell items to your own shop");
sendError(pl, "To add items, use /shop add");
return true;
}
ItemStack itemsToSell = pl.getItemInHand();
if (itemsToSell == null || itemsToSell.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to sell");
return true;
}
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(itemsToSell.getTypeId(), itemsToSell.getDurability());
if (entry == null || entry.refundPrice < 0) {
sendError(pl, "You cannot sell that item");
return true;
}
pl.setItemInHand(null);
String name = getItemName(itemsToSell);
pl.sendMessage(String.format(
"Your request to sell §B%d %s§F for §B$%.2f§F has been sent",
itemsToSell.getAmount(), name, entry.refundPrice * itemsToSell.getAmount()));
pl.sendMessage("§7You will be notified when this offer is accepted or rejected");
ShopEntry req = new ShopEntry();
req.setItem(itemsToSell);
req.refundPrice = entry.refundPrice;
SellRequest request = new SellRequest(shop, req, pl.getName());
sendNotification(shop.owner, request);
} else if (action.equalsIgnoreCase("pending") ||
action.equalsIgnoreCase("p") ||
action.equalsIgnoreCase("notifications") ||
action.equalsIgnoreCase("n")) {
showNotification(pl);
} else if (action.equalsIgnoreCase("accept") ||
action.equalsIgnoreCase("yes") ||
action.equalsIgnoreCase("a") ||
action.equalsIgnoreCase("claim") ||
action.equalsIgnoreCase("c")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.accept(pl))
notifications.removeFirst();
} else if (n instanceof Claimable) {
Claimable c = (Claimable) n;
if (c.claim(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("reject") ||
action.equalsIgnoreCase("no")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.reject(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("skip") ||
action.equalsIgnoreCase("sk")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
notifications.add(notifications.removeFirst());
showNotification(pl);
} else if (action.equalsIgnoreCase("lookup")) {
if (args.length < 2) {
sendError(pl, Help.lookup.toUsageString());
return true;
}
Long alias = getItemFromAlias(args[1]);
if (alias == null) {
sendError(pl, "Alias not found");
return true;
}
int id = (int) (alias >> 16);
int damage = (int) (alias & 0xFFFF);
sender.sendMessage(String.format("%s is an alias for %d:%d", args[1], id, damage));
} else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = Help.getHelpFor(helpCmd);
if (h == null) {
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
return true;
}
pl.sendMessage(h.toHelpString());
} else {
Help.showHelp(pl, selection);
}
return true;
}
return false;
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Block b = event.getClickedBlock();
if (b == null || b.getTypeId() != SIGN) return;
Shop shop = shops.get(b.getLocation());
if (shop == null) return;
Player pl = event.getPlayer();
boolean isOwner = shop.owner.equals(pl.getName());
ShopSelection selection = selectedShops.get(pl);
if (selection == null) {
selection = new ShopSelection();
selectedShops.put(pl, selection);
}
if (selection.shop == shop) {
int pages = shop.getPages();
if (pages == 0) {
selection.page = 0;
} else {
int delta = event.getAction() == Action.LEFT_CLICK_BLOCK ? -1 : 1;
selection.page = (((selection.page + delta) % pages) + pages) % pages;
}
pl.sendMessage("");
pl.sendMessage("");
} else {
selection.isOwner = isOwner;
selection.shop = shop;
selection.page = 0;
pl.sendMessage(new String[] {
isOwner ? "§FWelcome to your shop." :
String.format("§FWelcome to §B%s§F's shop.", shop.owner),
"§7For help with shops, type §3/shop help§7."
});
}
showListing(pl, selection);
event.setCancelled(true);
if (event.getAction() == Action.LEFT_CLICK_BLOCK)
b.getState().update();
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerJoin(PlayerJoinEvent event){
ArrayDeque<Notification> p = getNotifications(event.getPlayer());
if (!p.isEmpty())
event.getPlayer().sendMessage("You have shop notifications. Use §B/shop pending§F to view them");
}
/**
* Attempts to find an item which matches the given item name (alias).
* @param alias the item name
* @return a Long which contains the item ID and damage value as follows: (id << 16) | (damage)
*/
public Long getItemFromAlias(String alias) {
alias = alias.toLowerCase();
return aliases.get(alias);
}
/**
* Gets the name of an item.
* @param item an item stack
* @return the item's name
*/
public String getItemName(ItemStack item) {
return getItemName(item.getTypeId(), item.getDurability());
}
/**
* Gets the name of an item.
* @param item an item stack
* @return the item's name
*/
public String getItemName(ShopEntry entry) {
return getItemName(entry.itemID, entry.itemDamage);
}
/**
* Gets the name of an item.
* @param id the item's id
* @param damage the item's damage value (durability)
* @return the item's name
*/
public String getItemName(int id, int damage) {
String name = itemNames.get((long) id << 16 | damage);
if (name == null) {
name = itemNames.get((long) id << 16);
if (name == null) return String.format("%d:%d", id, damage);
}
return name;
}
/**
* Gets a list of notifications for a player.
* @param pl the player
* @return the player's notifications
*/
public ArrayDeque<Notification> getNotifications(Player pl) {
return getNotifications(pl.getName());
}
/**
* Gets a list of notifications for a player.
* @param player the player
* @return the player's notifications
*/
public ArrayDeque<Notification> getNotifications(String player) {
ArrayDeque<Notification> n = pending.get(player);
if (n == null) {
n = new ArrayDeque<Notification>();
pending.put(player, n);
}
return n;
}
/**
* Shows a player his/her most recent notification.
* Also shows the notification count.
* @param pl the player
*/
public void showNotification(Player pl) {
showNotification(pl, true);
}
/**
* Shows a player his/her most recent notification.
* @param pl the player
* @param showCount whether the notification count should be shown as well
*/
public void showNotification(Player pl, boolean showCount) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
if (showCount)
pl.sendMessage("§7You have no notifications");
return;
}
if (showCount) {
int size = notifications.size();
pl.sendMessage(size == 1 ? "§7You have §31§7 notification" : String.format("§7You have §3%d§7 notifications", size));
}
Notification n = notifications.getFirst();
pl.sendMessage(n.getMessage(pl));
if (n instanceof Request)
pl.sendMessage("§7Use §3/shop accept§7 and §3/shop reject§7 to manage this request");
else if (n instanceof Claimable)
pl.sendMessage("§7Use §3/shop claim§7 to claim and remove this notification");
else notifications.removeFirst();
}
/**
* Sends a notification to a player.
* @param pl the player
* @param n the notification
*/
public void sendNotification(Player pl, Notification n) {
sendNotification(pl.getName(), n);
}
/**
* Sends a notification to a player.
* @param player the player
* @param n the notification
*/
public void sendNotification(String player, Notification n) {
ArrayDeque<Notification> ns = getNotifications(player);
ns.add(n);
Player pl = getServer().getPlayer(player);
if (pl != null && pl.isOnline())
showNotification(pl, false);
}
/**
* Checks whether an item stack will fit in a player's inventory.
* @param pl the player
* @param item the item
* @return whether the item will fit
*/
public static boolean inventoryFitsItem(Player pl, ItemStack item) {
int quantity = item.getAmount(),
id = item.getTypeId(),
damage = item.getDurability(),
max = item.getMaxStackSize();
Inventory inv = pl.getInventory();
ItemStack[] contents = inv.getContents();
ItemStack s;
if (max == -1) max = inv.getMaxStackSize();
for (int i = 0; i < contents.length; ++i) {
if ((s = contents[i]) == null || s.getTypeId() == 0) {
quantity -= max;
if (quantity <= 0) return true;
continue;
}
if (s.getTypeId() == id && s.getDurability() == damage) {
quantity -= max - s.getAmount();
if (quantity <= 0) return true;
}
}
return false;
}
/**
* Informs a player of an error.
* @param sender the player
* @param message the error message
*/
public static void sendError(CommandSender sender, String message) {
sender.sendMessage("§C" + message);
}
/**
* Show a page of a shop's inventory listing.
* @param sender the player to which the listing is shown
* @param selection the player's shop selection
*/
public static void showListing(CommandSender sender, ShopSelection selection) {
Shop shop = selection.shop;
int pages = shop.getPages();
if (pages == 0) {
sender.sendMessage(CommandHelp.header("Empty"));
sender.sendMessage("");
sender.sendMessage("This shop has no items");
int stop = Shop.ITEMS_PER_PAGE - 2;
if (selection.isOwner) {
sender.sendMessage("Use /shop add to add items");
--stop;
}
for (int i = 0; i < stop; ++i) {
sender.sendMessage("");
}
return;
}
sender.sendMessage(CommandHelp.header(String.format("Page %d/%d", selection.page + 1, pages)));
int i = selection.page * Shop.ITEMS_PER_PAGE,
stop = (selection.page + 1) * Shop.ITEMS_PER_PAGE,
max = Math.min(stop, shop.getInventorySize());
for (; i < max; ++i)
sender.sendMessage(shop.getEntryAt(i).toString());
for (; i < stop; ++i)
sender.sendMessage("");
}
/**
* Loads the alias map from the aliases.txt resource.
*/
public void loadAliases() {
InputStream stream = getResource("aliases.txt");
if (stream == null)
return;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = br.readLine()) != null) {
if (line.length() == 0 || line.charAt(0) == '#') continue;
Scanner current = new Scanner(line);
String name = current.next();
int id = current.nextInt();
int damage = current.hasNext() ? current.nextInt() : 0;
aliases.put(name, (long) id << 16 | damage);
}
stream.close();
} catch (IOException e) {
log.warning("Failed to load aliases: " + e.toString());
}
}
/**
* Loads the item names map from the items.txt resource.
*/
public void loadItemNames() {
InputStream stream = getResource("items.txt");
if (stream == null)
return;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = br.readLine();
while (line != null) {
if (line.length() == 0 || line.charAt(0) == '#') continue;
Scanner current = new Scanner(line);
int id = current.nextInt(),
damage = 0;
String name = "";
while (current.hasNext()) {
name += ' ' + current.next();
}
if (name.length() == 0) {
log.info(String.format("%s: %s", line, name));
break;
}
itemNames.put((long) id << 16 | damage, name.substring(1));
line = br.readLine();
if (line != null && line.charAt(0) == '|') {
do {
if (line.length() == 0 || line.charAt(0) == '#') continue;
current = new Scanner(line);
if (!current.next().equals("|")) break;
if (!current.hasNextInt(16)) break;
damage = current.nextInt(16);
name = "";
while (current.hasNext()) {
name += ' ' + current.next();
}
itemNames.put((long) id << 16 | damage, name.substring(1));
} while ((line = br.readLine()) != null);
}
}
stream.close();
} catch (IOException e) {
log.warning("Failed to load item names: " + e.toString());
}
}
/**
* Sets up Vault.
* @return true on success, false otherwise
*/
private boolean economySetup() {
if (getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false;
}
econ = rsp.getProvider();
return econ != null;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
return true;
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
Help.showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("mk")) {
if (args.length < 2) {
sendError(pl, Help.create.toUsageString());
return true;
}
if (!sender.hasPermission("shops.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
} else if (action.equalsIgnoreCase("add") ||
action.equalsIgnoreCase("+") ||
action.equalsIgnoreCase("ad")) {
if (args.length < 2) {
sendError(pl, Help.add.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!selection.isOwner && !pl.hasPermission("shops.admin")) {
sendError(pl, "You cannot add items to this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[1])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.add.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[2])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.add.toUsageString());
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wisth to add to this shop");
return true;
}
if (selection.shop.containsItem(stack)) {
sendError(pl, "That item has already been added to this shop");
sendError(pl, "Use /shop restock to restock");
return true;
}
ShopEntry newEntry = new ShopEntry();
newEntry.setItem(stack);
newEntry.retailPrice = retailAmount;
newEntry.refundPrice = refundAmount;
selection.shop.addEntry(newEntry);
pl.setItemInHand(null);
} else if ((action.equalsIgnoreCase("restock") ||
action.equalsIgnoreCase("r"))) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!selection.isOwner && !pl.hasPermission("shops.admin")) {
sendError(pl, "You cannot restock this shop");
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to add to this shop");
return true;
}
ShopEntry entry = selection.shop.findEntry(stack);
if (entry == null) {
sendError(pl, "That item has not been added to this shop");
sendError(pl, "Use /shop add to add a new item");
return true;
}
entry.setAmount(entry.item.getAmount() + stack.getAmount());
pl.setItemInHand(null);
} else if (action.equalsIgnoreCase("set")) {
if (!selection.isOwner && !pl.hasPermission("shop.admin")) {
sendError(pl, "You cannot change this shop's prices");
return true;
}
if (args.length < 3) {
sendError(pl, Help.set.toUsageString());
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[2])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.set.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[3])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.set.toUsageString());
return true;
}
entry.retailPrice = retailAmount;
entry.refundPrice = refundAmount;
} else if (action.equalsIgnoreCase("buy") ||
action.equalsIgnoreCase("b")) {
if (args.length < 3) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (selection.isOwner && !pl.hasPermission("shops.self")) {
sendError(pl, "You cannot buy items from this shop");
return true;
}
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (amount <= 0) {
sendError(pl, "You must buy a positive number of this item");
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
if (entry.item.getAmount() < amount) {
sendError(pl, "There are not enough of that item in the shop");
return true;
}
int max = entry.item.getMaxStackSize();
String itemName = getItemName(entry.item);
if (max > -1 && amount > max) {
sendError(pl, String.format("You may only buy §B%d %s§C at once", max, itemName));
return true;
}
if(!(econ.has(pl.getName(), amount * entry.retailPrice))){
sendError(pl, "You do not have sufficient funds");
return true;
}
ItemStack purchased = entry.item.clone();
purchased.setAmount(amount);
HashMap<Integer, ItemStack> overflow = pl.getInventory().addItem(purchased);
int refunded = 0;
if (overflow.size() > 0) {
refunded = overflow.get(0).getAmount();
if (overflow.size() == amount) {
sendError(pl, "You do not have any room in your inventory");
return true;
}
sender.sendMessage(String.format(
"Only §B%d %s§F fit in your inventory. You were charged §B$%.2f§F.",
amount - refunded, itemName, (amount - refunded) * entry.retailPrice));
} else {
sender.sendMessage(String.format(
"You bought §B%d %s§F for §B$%.2f§F.",
amount, itemName, amount * entry.retailPrice));
}
econ.withdrawPlayer(pl.getName(), (amount - refunded) * entry.retailPrice);
entry.item.setAmount(entry.item.getAmount() - (amount - refunded));
econ.depositPlayer(shop.owner, (amount - refunded) * entry.retailPrice);
} else if (action.equalsIgnoreCase("sell") ||
action.equalsIgnoreCase("s")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (selection.isOwner && !pl.hasPermission("shops.self")) {
sendError(pl, "You cannot sell items to your own shop");
sendError(pl, "To add items, use /shop add");
return true;
}
ItemStack itemsToSell = pl.getItemInHand();
if (itemsToSell == null || itemsToSell.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to sell");
return true;
}
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(itemsToSell.getTypeId(), itemsToSell.getDurability());
if (entry == null || entry.refundPrice < 0) {
sendError(pl, "You cannot sell that item");
return true;
}
pl.setItemInHand(null);
String name = getItemName(itemsToSell);
pl.sendMessage(String.format(
"Your request to sell §B%d %s§F for §B$%.2f§F has been sent",
itemsToSell.getAmount(), name, entry.refundPrice * itemsToSell.getAmount()));
pl.sendMessage("§7You will be notified when this offer is accepted or rejected");
ShopEntry req = new ShopEntry();
req.setItem(itemsToSell);
req.refundPrice = entry.refundPrice;
SellRequest request = new SellRequest(shop, req, pl.getName());
sendNotification(shop.owner, request);
} else if (action.equalsIgnoreCase("pending") ||
action.equalsIgnoreCase("p") ||
action.equalsIgnoreCase("notifications") ||
action.equalsIgnoreCase("n")) {
showNotification(pl);
} else if (action.equalsIgnoreCase("accept") ||
action.equalsIgnoreCase("yes") ||
action.equalsIgnoreCase("a") ||
action.equalsIgnoreCase("claim") ||
action.equalsIgnoreCase("c")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.accept(pl))
notifications.removeFirst();
} else if (n instanceof Claimable) {
Claimable c = (Claimable) n;
if (c.claim(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("reject") ||
action.equalsIgnoreCase("no")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.reject(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("skip") ||
action.equalsIgnoreCase("sk")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
notifications.add(notifications.removeFirst());
showNotification(pl);
} else if (action.equalsIgnoreCase("lookup")) {
if (args.length < 2) {
sendError(pl, Help.lookup.toUsageString());
return true;
}
Long alias = getItemFromAlias(args[1]);
if (alias == null) {
sendError(pl, "Alias not found");
return true;
}
int id = (int) (alias >> 16);
int damage = (int) (alias & 0xFFFF);
sender.sendMessage(String.format("%s is an alias for %d:%d", args[1], id, damage));
} else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = Help.getHelpFor(helpCmd);
if (h == null) {
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
return true;
}
pl.sendMessage(h.toHelpString());
} else {
Help.showHelp(pl, selection);
}
return true;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (command.getName().equalsIgnoreCase("shop")) {
if (!(sender instanceof Player)) {
sendError(sender, "/shop can only be used by a player");
return true;
}
Player pl = (Player) sender;
ShopSelection selection = selectedShops.get(pl);
if (args.length == 0) {
Help.showHelp(pl, selection);
return true;
}
String action = args[0];
if (action.equalsIgnoreCase("create") ||
action.equalsIgnoreCase("mk")) {
if (args.length < 2) {
sendError(pl, Help.create.toUsageString());
return true;
}
if (!sender.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot create shops");
return true;
}
Location loc = pl.getLocation();
Block b = loc.getBlock();
byte angle = (byte) ((((int) loc.getYaw() + 225) / 90) << 2);
b.setTypeIdAndData(SIGN, angle, false);
Sign sign = (Sign) b.getState();
String owner = args[1];
sign.setLine(1, (owner.length() < 13 ? owner : owner.substring(0, 12) + '…') + "'s");
sign.setLine(2, "shop");
sign.update();
Shop shop = new Shop();
shop.owner = owner;
shop.location = b.getLocation();
shops.put(shop.location, shop);
} else if (action.equalsIgnoreCase("remove") ||
action.equalsIgnoreCase("rm")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!pl.hasPermission("shop.admin") && !selection.isOwner) {
sendError(pl, "You cannot remove this shop");
return true;
}
Location loc = selection.shop.location;
Block b = loc.getBlock();
Sign sign = (Sign) b.getState();
sign.setLine(0, "This shop is");
sign.setLine(1, "out of");
sign.setLine(2, "business.");
sign.setLine(3, "Sorry! D:");
sign.update();
shops.remove(loc);
pl.sendMessage("§B" + selection.shop.owner + "§F's shop has been removed");
} else if (action.equalsIgnoreCase("add") ||
action.equalsIgnoreCase("+") ||
action.equalsIgnoreCase("ad")) {
if (args.length < 2) {
sendError(pl, Help.add.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!selection.isOwner && !pl.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot add items to this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[1])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.add.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[2])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.add.toUsageString());
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wisth to add to this shop");
return true;
}
if (selection.shop.containsItem(stack)) {
sendError(pl, "That item has already been added to this shop");
sendError(pl, "Use /shop restock to restock");
return true;
}
ShopEntry newEntry = new ShopEntry();
newEntry.setItem(stack);
newEntry.retailPrice = retailAmount;
newEntry.refundPrice = refundAmount;
selection.shop.addEntry(newEntry);
pl.setItemInHand(null);
} else if ((action.equalsIgnoreCase("restock") ||
action.equalsIgnoreCase("r"))) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (!selection.isOwner && !pl.hasPermission("swornshop.admin")) {
sendError(pl, "You cannot restock this shop");
return true;
}
ItemStack stack = pl.getItemInHand();
if (stack == null || stack.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to add to this shop");
return true;
}
ShopEntry entry = selection.shop.findEntry(stack);
if (entry == null) {
sendError(pl, "That item has not been added to this shop");
sendError(pl, "Use /shop add to add a new item");
return true;
}
entry.setAmount(entry.item.getAmount() + stack.getAmount());
pl.setItemInHand(null);
} else if (action.equalsIgnoreCase("set")) {
if (!selection.isOwner && !pl.hasPermission("shop.admin")) {
sendError(pl, "You cannot change this shop's prices");
return true;
}
if (args.length < 3) {
sendError(pl, Help.set.toUsageString());
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
float retailAmount, refundAmount;
try {
retailAmount = Math.round(100f * Float.parseFloat(args[2])) / 100f;
} catch (NumberFormatException e) {
sendError(pl, "Invalid buy price");
sendError(pl, Help.set.toUsageString());
return true;
}
try {
refundAmount = args.length > 2 ? Math.round(100f * Float.parseFloat(args[3])) / 100f : -1;
} catch (NumberFormatException e) {
sendError(pl, "Invalid sell price");
sendError(pl, Help.set.toUsageString());
return true;
}
entry.retailPrice = retailAmount;
entry.refundPrice = refundAmount;
} else if (action.equalsIgnoreCase("buy") ||
action.equalsIgnoreCase("b")) {
if (args.length < 3) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (selection.isOwner && !pl.hasPermission("swornshop.self")) {
sendError(pl, "You cannot buy items from this shop");
return true;
}
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
sendError(pl, Help.buy.toUsageString());
return true;
}
if (amount <= 0) {
sendError(pl, "You must buy a positive number of this item");
return true;
}
long item = getItemFromAlias(args[1]);
int id = (int) (item >> 16);
short damage = (short) (item & 0xFFFF);
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(id, damage);
if (entry == null) {
sendError(pl, "That item is not in this shop");
return true;
}
if (entry.item.getAmount() < amount) {
sendError(pl, "There are not enough of that item in the shop");
return true;
}
int max = entry.item.getMaxStackSize();
String itemName = getItemName(entry.item);
if (max > -1 && amount > max) {
sendError(pl, String.format("You may only buy §B%d %s§C at once", max, itemName));
return true;
}
if(!(econ.has(pl.getName(), amount * entry.retailPrice))){
sendError(pl, "You do not have sufficient funds");
return true;
}
ItemStack purchased = entry.item.clone();
purchased.setAmount(amount);
HashMap<Integer, ItemStack> overflow = pl.getInventory().addItem(purchased);
int refunded = 0;
if (overflow.size() > 0) {
refunded = overflow.get(0).getAmount();
if (overflow.size() == amount) {
sendError(pl, "You do not have any room in your inventory");
return true;
}
sender.sendMessage(String.format(
"Only §B%d %s§F fit in your inventory. You were charged §B$%.2f§F.",
amount - refunded, itemName, (amount - refunded) * entry.retailPrice));
} else {
sender.sendMessage(String.format(
"You bought §B%d %s§F for §B$%.2f§F.",
amount, itemName, amount * entry.retailPrice));
}
econ.withdrawPlayer(pl.getName(), (amount - refunded) * entry.retailPrice);
entry.item.setAmount(entry.item.getAmount() - (amount - refunded));
econ.depositPlayer(shop.owner, (amount - refunded) * entry.retailPrice);
} else if (action.equalsIgnoreCase("sell") ||
action.equalsIgnoreCase("s")) {
if (selection == null) {
sendError(pl, "You must select a shop");
return true;
}
if (selection.isOwner && !pl.hasPermission("swornshop.self")) {
sendError(pl, "You cannot sell items to your own shop");
sendError(pl, "To add items, use /shop add");
return true;
}
ItemStack itemsToSell = pl.getItemInHand();
if (itemsToSell == null || itemsToSell.getTypeId() == 0) {
sendError(pl, "You must be holding the item you wish to sell");
return true;
}
Shop shop = selection.shop;
ShopEntry entry = shop.findEntry(itemsToSell.getTypeId(), itemsToSell.getDurability());
if (entry == null || entry.refundPrice < 0) {
sendError(pl, "You cannot sell that item");
return true;
}
pl.setItemInHand(null);
String name = getItemName(itemsToSell);
pl.sendMessage(String.format(
"Your request to sell §B%d %s§F for §B$%.2f§F has been sent",
itemsToSell.getAmount(), name, entry.refundPrice * itemsToSell.getAmount()));
pl.sendMessage("§7You will be notified when this offer is accepted or rejected");
ShopEntry req = new ShopEntry();
req.setItem(itemsToSell);
req.refundPrice = entry.refundPrice;
SellRequest request = new SellRequest(shop, req, pl.getName());
sendNotification(shop.owner, request);
} else if (action.equalsIgnoreCase("pending") ||
action.equalsIgnoreCase("p") ||
action.equalsIgnoreCase("notifications") ||
action.equalsIgnoreCase("n")) {
showNotification(pl);
} else if (action.equalsIgnoreCase("accept") ||
action.equalsIgnoreCase("yes") ||
action.equalsIgnoreCase("a") ||
action.equalsIgnoreCase("claim") ||
action.equalsIgnoreCase("c")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.accept(pl))
notifications.removeFirst();
} else if (n instanceof Claimable) {
Claimable c = (Claimable) n;
if (c.claim(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("reject") ||
action.equalsIgnoreCase("no")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
Notification n = notifications.getFirst();
if (n instanceof Request) {
Request r = (Request) n;
if (r.reject(pl))
notifications.removeFirst();
}
showNotification(pl);
} else if (action.equalsIgnoreCase("skip") ||
action.equalsIgnoreCase("sk")) {
ArrayDeque<Notification> notifications = getNotifications(pl);
if (notifications.isEmpty()) {
sendError(pl, "You have no notifications");
return true;
}
notifications.add(notifications.removeFirst());
showNotification(pl);
} else if (action.equalsIgnoreCase("lookup")) {
if (args.length < 2) {
sendError(pl, Help.lookup.toUsageString());
return true;
}
Long alias = getItemFromAlias(args[1]);
if (alias == null) {
sendError(pl, "Alias not found");
return true;
}
int id = (int) (alias >> 16);
int damage = (int) (alias & 0xFFFF);
sender.sendMessage(String.format("%s is an alias for %d:%d", args[1], id, damage));
} else if ((action.equalsIgnoreCase("help") ||
action.equalsIgnoreCase("h")) &&
args.length > 1) {
String helpCmd = args[1];
CommandHelp h = Help.getHelpFor(helpCmd);
if (h == null) {
sendError(pl, String.format("'/shop %s' is not an action", helpCmd));
return true;
}
pl.sendMessage(h.toHelpString());
} else {
Help.showHelp(pl, selection);
}
return true;
}
return false;
}
|
diff --git a/src/com/cleverua/bb/example/AppSettingsScreen.java b/src/com/cleverua/bb/example/AppSettingsScreen.java
index ba42521..0480ac1 100644
--- a/src/com/cleverua/bb/example/AppSettingsScreen.java
+++ b/src/com/cleverua/bb/example/AppSettingsScreen.java
@@ -1,62 +1,62 @@
package com.cleverua.bb.example;
import com.cleverua.bb.settings.SettingsException;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
public class AppSettingsScreen extends MainScreen {
private static final String SETTINGS_SUCCESSFUL_DIALOG = "Settings were saved successfully!";
private static final String SAVE_BUTTON_LABEL = "Save settings";
private static final String CHECK_BOX_LABEL = "User choice";
private CheckboxField userChoice;
private EditField userText;
public AppSettingsScreen() {
super();
initUI();
}
private void initUI() {
try {
AppSettingsApplication.getSettings().initialize();
} catch (SettingsException e) {
Dialog.alert("Unable to load settings: " + e);
}
boolean userChoiceSetting = AppSettingsApplication.getSettingsDelegate().getUserChoice();
userChoice = new CheckboxField(CHECK_BOX_LABEL, userChoiceSetting, USE_ALL_WIDTH);
userText = new EditField(USE_ALL_WIDTH);
String userTextSetting = AppSettingsApplication.getSettingsDelegate().getUserText();
userText.setText(userTextSetting);
add(userText);
add(userChoice);
userText.setFocus();
ButtonField saveButton = new ButtonField(SAVE_BUTTON_LABEL, FIELD_HCENTER);
saveButton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field arg0, int arg1) {
AppSettingsApplication.getSettingsDelegate().setUserChoice(userChoice.getChecked());
AppSettingsApplication.getSettingsDelegate().setUserText(userText.getText());
try {
AppSettingsApplication.getSettings().flush();
- } catch (Exception e) {
+ Dialog.inform(SETTINGS_SUCCESSFUL_DIALOG);
+ } catch (SettingsException e) {
Dialog.alert("Unable to save settings: " + e);
}
- Dialog.inform(SETTINGS_SUCCESSFUL_DIALOG);
}
});
setStatus(saveButton);
}
protected boolean onSavePrompt() {
return true;
}
}
| false | true | private void initUI() {
try {
AppSettingsApplication.getSettings().initialize();
} catch (SettingsException e) {
Dialog.alert("Unable to load settings: " + e);
}
boolean userChoiceSetting = AppSettingsApplication.getSettingsDelegate().getUserChoice();
userChoice = new CheckboxField(CHECK_BOX_LABEL, userChoiceSetting, USE_ALL_WIDTH);
userText = new EditField(USE_ALL_WIDTH);
String userTextSetting = AppSettingsApplication.getSettingsDelegate().getUserText();
userText.setText(userTextSetting);
add(userText);
add(userChoice);
userText.setFocus();
ButtonField saveButton = new ButtonField(SAVE_BUTTON_LABEL, FIELD_HCENTER);
saveButton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field arg0, int arg1) {
AppSettingsApplication.getSettingsDelegate().setUserChoice(userChoice.getChecked());
AppSettingsApplication.getSettingsDelegate().setUserText(userText.getText());
try {
AppSettingsApplication.getSettings().flush();
} catch (Exception e) {
Dialog.alert("Unable to save settings: " + e);
}
Dialog.inform(SETTINGS_SUCCESSFUL_DIALOG);
}
});
setStatus(saveButton);
}
| private void initUI() {
try {
AppSettingsApplication.getSettings().initialize();
} catch (SettingsException e) {
Dialog.alert("Unable to load settings: " + e);
}
boolean userChoiceSetting = AppSettingsApplication.getSettingsDelegate().getUserChoice();
userChoice = new CheckboxField(CHECK_BOX_LABEL, userChoiceSetting, USE_ALL_WIDTH);
userText = new EditField(USE_ALL_WIDTH);
String userTextSetting = AppSettingsApplication.getSettingsDelegate().getUserText();
userText.setText(userTextSetting);
add(userText);
add(userChoice);
userText.setFocus();
ButtonField saveButton = new ButtonField(SAVE_BUTTON_LABEL, FIELD_HCENTER);
saveButton.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field arg0, int arg1) {
AppSettingsApplication.getSettingsDelegate().setUserChoice(userChoice.getChecked());
AppSettingsApplication.getSettingsDelegate().setUserText(userText.getText());
try {
AppSettingsApplication.getSettings().flush();
Dialog.inform(SETTINGS_SUCCESSFUL_DIALOG);
} catch (SettingsException e) {
Dialog.alert("Unable to save settings: " + e);
}
}
});
setStatus(saveButton);
}
|
diff --git a/src/main/java/com/github/rconner/anansi/PreOrderTraverser.java b/src/main/java/com/github/rconner/anansi/PreOrderTraverser.java
index b9d7e2e..cd271bb 100644
--- a/src/main/java/com/github/rconner/anansi/PreOrderTraverser.java
+++ b/src/main/java/com/github/rconner/anansi/PreOrderTraverser.java
@@ -1,130 +1,132 @@
/*
* Copyright (c) 2012 Ray A. Conner
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.github.rconner.anansi;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Package implementation of the Traverser returned by {@link Traversers#preOrder(Traverser)}.
*
* @param <V>
* @param <E>
*/
final class PreOrderTraverser<V, E> implements Traverser<V, E> {
private final Traverser<V, E> adjacency;
PreOrderTraverser( final Traverser<V, E> adjacency ) {
this.adjacency = adjacency;
}
@Override
public Iterable<Walk<V, E>> apply( final V start ) {
return new Iterable<Walk<V, E>>() {
@Override
public Iterator<Walk<V, E>> iterator() {
return new PreOrderIterator<V, E>( start, adjacency );
}
};
}
private static final class PreOrderIterator<V, E> implements PruningIterator<Walk<V, E>> {
/**
* The supplied adjacency function.
*/
private final Traverser<V, E> adjacency;
/**
* A stack of Iterators. The next object to be returned is from the topmost Iterator which has something left to
* return. As objects are returned, the above function is used to create new Iterators which are pushed onto the
* stack, even if they are empty.
*/
private final LinkedList<Iterator<Walk<V, E>>> iteratorStack = Lists.newLinkedList();
/**
* True if this iterator is in a valid state for calling remove() or prune().
*/
private boolean canMutate = false;
/**
* Collects adjacency walks and produces the compound walks to return.
*/
private final Walk.Builder<V, E> builder;
PreOrderIterator( final V start, final Traverser<V, E> adjacency ) {
this.adjacency = adjacency;
iteratorStack.addFirst( Iterators.singletonIterator( Walk.<V, E>empty( start ) ) );
builder = Walk.from( start );
}
@Override
public boolean hasNext() {
for( final Iterator<Walk<V, E>> iterator : iteratorStack ) {
if( iterator.hasNext() ) {
return true;
}
}
return false;
}
@Override
public Walk<V, E> next() {
while( !iteratorStack.isEmpty() ) {
if( iteratorStack.getFirst().hasNext() ) {
final Walk<V, E> result = iteratorStack.getFirst().next();
iteratorStack.addFirst( adjacency.apply( result.getTo() ).iterator() );
builder.add( result );
canMutate = true;
return builder.build();
}
iteratorStack.removeFirst();
- builder.pop();
+ if( !builder.isEmpty() ) {
+ builder.pop();
+ }
}
canMutate = false;
throw new NoSuchElementException();
}
@Override
public void remove() {
Preconditions.checkState( canMutate );
iteratorStack.removeFirst();
builder.pop();
iteratorStack.getFirst().remove();
canMutate = false;
}
@Override
public void prune() {
Preconditions.checkState( canMutate );
iteratorStack.removeFirst();
builder.pop();
canMutate = false;
}
}
}
| true | true | public Walk<V, E> next() {
while( !iteratorStack.isEmpty() ) {
if( iteratorStack.getFirst().hasNext() ) {
final Walk<V, E> result = iteratorStack.getFirst().next();
iteratorStack.addFirst( adjacency.apply( result.getTo() ).iterator() );
builder.add( result );
canMutate = true;
return builder.build();
}
iteratorStack.removeFirst();
builder.pop();
}
canMutate = false;
throw new NoSuchElementException();
}
| public Walk<V, E> next() {
while( !iteratorStack.isEmpty() ) {
if( iteratorStack.getFirst().hasNext() ) {
final Walk<V, E> result = iteratorStack.getFirst().next();
iteratorStack.addFirst( adjacency.apply( result.getTo() ).iterator() );
builder.add( result );
canMutate = true;
return builder.build();
}
iteratorStack.removeFirst();
if( !builder.isEmpty() ) {
builder.pop();
}
}
canMutate = false;
throw new NoSuchElementException();
}
|
diff --git a/src/test/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/Tv2PBCoreMapperTest.java b/src/test/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/Tv2PBCoreMapperTest.java
index 9fab6f0..2e54ea4 100644
--- a/src/test/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/Tv2PBCoreMapperTest.java
+++ b/src/test/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/Tv2PBCoreMapperTest.java
@@ -1,45 +1,45 @@
package dk.statsbiblioteket.doms.ingest.reklamepbcoremapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import static junit.framework.Assert.assertEquals;
/**
* Test file generations.
*/
public class Tv2PBCoreMapperTest {
private static final File OUTPUTDIR = new File("target/testoutput");
@Before
public void setUp() {
OUTPUTDIR.mkdirs();
}
@After
public void tearDown() {
for (File file : OUTPUTDIR.listFiles()) {
file.delete();
}
OUTPUTDIR.delete();
}
@Test
public void testMapCsvDataToPBCoreFiles() throws Exception {
new Tv2PBCoreMapper().mapCsvDataToPBCoreFiles(new File(getClass().getClassLoader().getResource("199901_1.meta.utf8.csv").getPath()),
OUTPUTDIR);
File[] generatedFiles = OUTPUTDIR.listFiles();
assertEquals(226, generatedFiles.length);
for (File file : generatedFiles) {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
- assertEquals(41, d.getElementsByTagName("*").getLength());
+ assertEquals(42, d.getElementsByTagName("*").getLength());
//TODO Test stuff
}
}
}
| true | true | public void testMapCsvDataToPBCoreFiles() throws Exception {
new Tv2PBCoreMapper().mapCsvDataToPBCoreFiles(new File(getClass().getClassLoader().getResource("199901_1.meta.utf8.csv").getPath()),
OUTPUTDIR);
File[] generatedFiles = OUTPUTDIR.listFiles();
assertEquals(226, generatedFiles.length);
for (File file : generatedFiles) {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
assertEquals(41, d.getElementsByTagName("*").getLength());
//TODO Test stuff
}
}
| public void testMapCsvDataToPBCoreFiles() throws Exception {
new Tv2PBCoreMapper().mapCsvDataToPBCoreFiles(new File(getClass().getClassLoader().getResource("199901_1.meta.utf8.csv").getPath()),
OUTPUTDIR);
File[] generatedFiles = OUTPUTDIR.listFiles();
assertEquals(226, generatedFiles.length);
for (File file : generatedFiles) {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
assertEquals(42, d.getElementsByTagName("*").getLength());
//TODO Test stuff
}
}
|
diff --git a/tests/org.bonitasoft.studio.application.test/src/org/bonitasoft/studio/application/test/TestMenus.java b/tests/org.bonitasoft.studio.application.test/src/org/bonitasoft/studio/application/test/TestMenus.java
index 92bac124db..88881c1169 100644
--- a/tests/org.bonitasoft.studio.application.test/src/org/bonitasoft/studio/application/test/TestMenus.java
+++ b/tests/org.bonitasoft.studio.application.test/src/org/bonitasoft/studio/application/test/TestMenus.java
@@ -1,51 +1,51 @@
/**
* Copyright (C) 2010-2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bonitasoft.studio.application.test;
import junit.framework.TestCase;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
/**
* @author Romain Bioteau
*/
public class TestMenus extends TestCase {
public void testNbMenus() {
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String menus = "";
int nbRunMenus = 0;
for (MenuItem item : shell.getMenuBar().getItems()) {
menus += "\n"+item.getText();
- if (item.getText().toLowerCase().contains("run")) {
+ if (item.getText().toLowerCase().trim().equals("run")) {
nbRunMenus++;
}
}
- assertEquals("Run menu should not appears", 1, nbRunMenus);
+ assertEquals("Run menu should not appears", 0, nbRunMenus);
if(Platform.getProduct().getId().equals("org.bonitasoft.studioEx.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus,12, shell.getMenuBar().getItemCount());
} else if(Platform.getProduct().getId().equals("org.bonitasoft.studio.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus, 8, shell.getMenuBar().getItemCount());
}
}
}
| false | true | public void testNbMenus() {
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String menus = "";
int nbRunMenus = 0;
for (MenuItem item : shell.getMenuBar().getItems()) {
menus += "\n"+item.getText();
if (item.getText().toLowerCase().contains("run")) {
nbRunMenus++;
}
}
assertEquals("Run menu should not appears", 1, nbRunMenus);
if(Platform.getProduct().getId().equals("org.bonitasoft.studioEx.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus,12, shell.getMenuBar().getItemCount());
} else if(Platform.getProduct().getId().equals("org.bonitasoft.studio.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus, 8, shell.getMenuBar().getItemCount());
}
}
| public void testNbMenus() {
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
String menus = "";
int nbRunMenus = 0;
for (MenuItem item : shell.getMenuBar().getItems()) {
menus += "\n"+item.getText();
if (item.getText().toLowerCase().trim().equals("run")) {
nbRunMenus++;
}
}
assertEquals("Run menu should not appears", 0, nbRunMenus);
if(Platform.getProduct().getId().equals("org.bonitasoft.studioEx.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus,12, shell.getMenuBar().getItemCount());
} else if(Platform.getProduct().getId().equals("org.bonitasoft.studio.product")){
assertEquals("Menu bar polluted by third-party menus.\n available menu:"+menus, 8, shell.getMenuBar().getItemCount());
}
}
|
diff --git a/src/com/github/joakimpersson/tda367/model/tiles/walkable/Fire.java b/src/com/github/joakimpersson/tda367/model/tiles/walkable/Fire.java
index 25540dd..f720ddd 100644
--- a/src/com/github/joakimpersson/tda367/model/tiles/walkable/Fire.java
+++ b/src/com/github/joakimpersson/tda367/model/tiles/walkable/Fire.java
@@ -1,112 +1,112 @@
package com.github.joakimpersson.tda367.model.tiles.walkable;
import java.util.ArrayList;
import java.util.List;
import com.github.joakimpersson.tda367.model.constants.Direction;
import com.github.joakimpersson.tda367.model.constants.PointGiver;
import com.github.joakimpersson.tda367.model.player.Player;
import com.github.joakimpersson.tda367.model.tiles.Tile;
import com.github.joakimpersson.tda367.model.tiles.WalkableTile;
/**
*
* @author joakimpersson
* @modified Viktor Anderling
*
*/
public class Fire implements WalkableTile {
private Direction direction;
private String image;
private Player fireOwner;
public Fire(Player fireOwner, Direction direction) {
this.fireOwner = fireOwner;
this.direction = direction;
- if (this.direction == Direction.NONE) {
+ if (this.direction == null) {
+ this.image = "fire-area";
+ } else if (this.direction == Direction.NONE) {
this.image = "fire-mid";
} else if (this.direction.isHorizontal()) {
this.image = "fire-row";
} else if (this.direction.isVertical()) {
this.image = "fire-column";
- } else {
- this.image = "fire-area";
}
}
/**
* If a player enters a fire tile it should loose one hp. Since the tile's
* state is not changed it returns itself when the method is invoked
*
* @param The
* player who entered the tile
* @return Itself
*/
@Override
public Tile playerEnter(Player player) {
player.playerHit();
distributePlayerPoints(player);
return this;
}
/**
* Responsible for distributing the points the player that placed the fire
* deserves when another player walks into his fire
*
* @param targetPlayer
* The player that walked into the fire
*/
private void distributePlayerPoints(Player targetPlayer) {
List<PointGiver> pg = new ArrayList<PointGiver>();
if (!targetPlayer.isImmortal() && targetPlayer.isAlive()) {
targetPlayer.playerHit();
if (!fireOwner.equals(targetPlayer)) {
pg.add(PointGiver.PlayerHit);
if (!targetPlayer.isAlive()) {
pg.add(PointGiver.KillPlayer);
}
fireOwner.updatePlayerPoints(pg);
}
}
}
@Override
public boolean isWalkable() {
return true;
}
@Override
public String toString() {
return "Fire";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Fire other = (Fire) obj;
return this.direction.equals(other.direction)
&& this.fireOwner.equals(other.fireOwner);
}
@Override
public int hashCode() {
int sum = 0;
sum += direction.hashCode() * 13;
sum += fireOwner.hashCode() * 17;
return sum;
}
@Override
public String getTileType() {
return this.image;
}
}
| false | true | public Fire(Player fireOwner, Direction direction) {
this.fireOwner = fireOwner;
this.direction = direction;
if (this.direction == Direction.NONE) {
this.image = "fire-mid";
} else if (this.direction.isHorizontal()) {
this.image = "fire-row";
} else if (this.direction.isVertical()) {
this.image = "fire-column";
} else {
this.image = "fire-area";
}
}
| public Fire(Player fireOwner, Direction direction) {
this.fireOwner = fireOwner;
this.direction = direction;
if (this.direction == null) {
this.image = "fire-area";
} else if (this.direction == Direction.NONE) {
this.image = "fire-mid";
} else if (this.direction.isHorizontal()) {
this.image = "fire-row";
} else if (this.direction.isVertical()) {
this.image = "fire-column";
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java
index abd05939a..8198e6ee3 100644
--- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java
+++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/CVSRepositoryLocation.java
@@ -1,1219 +1,1219 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.core.connection;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.PlatformObject;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.CVSException;
import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin;
import org.eclipse.team.internal.ccvs.core.CVSStatus;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.core.ICVSFolder;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteFile;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteFolder;
import org.eclipse.team.internal.ccvs.core.ICVSRemoteResource;
import org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation;
import org.eclipse.team.internal.ccvs.core.IConnectionMethod;
import org.eclipse.team.internal.ccvs.core.IUserAuthenticator;
import org.eclipse.team.internal.ccvs.core.IUserInfo;
import org.eclipse.team.internal.ccvs.core.Policy;
import org.eclipse.team.internal.ccvs.core.client.Command;
import org.eclipse.team.internal.ccvs.core.client.Session;
import org.eclipse.team.internal.ccvs.core.client.Update;
import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot;
import org.eclipse.team.internal.ccvs.core.resources.RemoteFile;
import org.eclipse.team.internal.ccvs.core.resources.RemoteFolder;
import org.eclipse.team.internal.ccvs.core.resources.RemoteFolderTree;
import org.eclipse.team.internal.ccvs.core.resources.RemoteModule;
import org.eclipse.team.internal.ccvs.core.util.Assert;
import org.eclipse.team.internal.ccvs.core.util.KnownRepositories;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;
/**
* This class manages a CVS repository location.
*
* It provides the mapping between connection method name and the
* plugged in ICunnectionMethod.
*
* It parses location strings into instances.
*
* It provides a method to open a connection to the server along
* with a method to validate that connections can be made.
*
* It manages its user info using the plugged in IUserAuthenticator
* (unless a username and password are provided as part of the creation
* string, in which case, no authenticator is used).
*
* Instances must be disposed of when no longer needed in order to
* notify the authenticator so cached properties can be cleared
*
*/
public class CVSRepositoryLocation extends PlatformObject implements ICVSRepositoryLocation, IUserInfo {
/**
* The name of the preferences node in the CVS preferences that contains
* the known repositories as its children.
*/
public static final String PREF_REPOSITORIES_NODE = "repositories"; //$NON-NLS-1$
/*
* The name of the node in the default scope that has the default settings
* for a repository.
*/
private static final String DEFAULT_REPOSITORY_SETTINGS_NODE = "default_repository_settings"; //$NON-NLS-1$
// Preference keys used to persist the state of the location
public static final String PREF_LOCATION = "location"; //$NON-NLS-1$
public static final String PREF_SERVER_ENCODING = "encoding"; //$NON-NLS-1$
// server platform constants
public static final int UNDETERMINED_PLATFORM = 0;
public static final int CVS_SERVER = 1;
public static final int CVSNT_SERVER = 2;
public static final int UNSUPPORTED_SERVER = 3;
public static final int UNKNOWN_SERVER = 4;
// static variables for extension points
private static IUserAuthenticator authenticator;
private static IConnectionMethod[] pluggedInConnectionMethods = null;
// Locks for ensuring that authentication to a host is serialized
// so that invalid passwords do not result in account lockout
private static Map hostLocks = new HashMap();
private IConnectionMethod method;
private String user;
private String password;
private String host;
private int port;
private String root;
private boolean userFixed;
private boolean passwordFixed;
private boolean allowCaching;
private int serverPlatform = UNDETERMINED_PLATFORM;
public static final char COLON = ':';
public static final char HOST_SEPARATOR = '@';
public static final char PORT_SEPARATOR = '#';
public static final boolean STANDALONE_MODE = (System.getProperty("eclipse.cvs.standalone")==null) ? //$NON-NLS-1$
false :(new Boolean(System.getProperty("eclipse.cvs.standalone")).booleanValue()); //$NON-NLS-1$
// command to start remote cvs in server mode
private static final String INVOKE_SVR_CMD = "server"; //$NON-NLS-1$
// fields needed for caching the password
public static final String INFO_PASSWORD = "org.eclipse.team.cvs.core.password";//$NON-NLS-1$
public static final String INFO_USERNAME = "org.eclipse.team.cvs.core.username";//$NON-NLS-1$
public static final String AUTH_SCHEME = "";//$NON-NLS-1$
public static final URL FAKE_URL;
public static final String USER_VARIABLE = "{user}"; //$NON-NLS-1$
public static final String PASSWORD_VARIABLE = "{password}"; //$NON-NLS-1$
public static final String HOST_VARIABLE = "{host}"; //$NON-NLS-1$
public static final String PORT_VARIABLE = "{port}"; //$NON-NLS-1$
private static String extProxy; //$NON-NLS-1$
static {
URL temp = null;
try {
temp = new URL("http://org.eclipse.team.cvs.core");//$NON-NLS-1$
} catch (MalformedURLException e) {
// Should never fail
}
FAKE_URL = temp;
}
/**
* Return the preferences node whose child nodes are teh know repositories
* @return a preferences node
*/
public static Preferences getParentPreferences() {
return CVSProviderPlugin.getPlugin().getInstancePreferences().node(PREF_REPOSITORIES_NODE);
}
/**
* Return a preferences node that contains suitabel defaults for a
* repository location.
* @return a preferences node
*/
public static Preferences getDefaultPreferences() {
Preferences defaults = new DefaultScope().getNode(CVSProviderPlugin.ID).node(DEFAULT_REPOSITORY_SETTINGS_NODE);
defaults.put(PREF_SERVER_ENCODING, getDefaultEncoding());
return defaults;
}
private static String getDefaultEncoding() {
return System.getProperty("file.encoding", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Set the proxy connection method that is to be used when a
* repository location has the ext connection method. This is
* usefull with the extssh connection method as it can be used to
* kepp the sandbox compatible with the command line client.
* @param string
*/
public static void setExtConnectionMethodProxy(String string) {
extProxy = string;
}
/**
* Validate whether the given string is a valid registered connection method
* name.
* @param methodName the method name
* @return whether the given string is a valid registered connection method
* name
*/
public static boolean validateConnectionMethod(String methodName) {
Assert.isNotNull(methodName);
IConnectionMethod[] methods = getPluggedInConnectionMethods();
for (int i=0;i<methods.length;i++) {
if (methodName.equals(methods[i].getName()))
return true;
}
return false;
}
/**
* Create a repository location instance from the given properties.
* The supported properties are:
*
* connection The connection method to be used
* user The username for the connection (optional)
* password The password used for the connection (optional)
* host The host where the repository resides
* port The port to connect to (optional)
* root The server directory where the repository is located
* encoding The file system encoding of the server
*/
public static CVSRepositoryLocation fromProperties(Properties configuration) throws CVSException {
// We build a string to allow validation of the components that are provided to us
String connection = configuration.getProperty("connection");//$NON-NLS-1$
if (connection == null)
connection = "pserver";//$NON-NLS-1$
IConnectionMethod method = getPluggedInConnectionMethod(connection);
if (method == null)
throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE, Policy.bind("CVSRepositoryLocation.methods", new Object[] {getPluggedInConnectionMethodNames()}), null));//$NON-NLS-1$
String user = configuration.getProperty("user");//$NON-NLS-1$
if (user.length() == 0)
user = null;
String password = configuration.getProperty("password");//$NON-NLS-1$
if (user == null)
password = null;
String host = configuration.getProperty("host");//$NON-NLS-1$
if (host == null)
throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE, Policy.bind("CVSRepositoryLocation.hostRequired"), null));//$NON-NLS-1$
String portString = configuration.getProperty("port");//$NON-NLS-1$
int port;
if (portString == null)
port = ICVSRepositoryLocation.USE_DEFAULT_PORT;
else
port = Integer.parseInt(portString);
String root = configuration.getProperty("root");//$NON-NLS-1$
if (root == null)
throw new CVSException(new Status(IStatus.ERROR, CVSProviderPlugin.ID, TeamException.UNABLE, Policy.bind("CVSRepositoryLocation.rootRequired"), null));//$NON-NLS-1$
root = root.replace('\\', '/');
String encoding = configuration.getProperty("encoding"); //$NON-NLS-1$
return new CVSRepositoryLocation(method, user, password, host, port, root, encoding, user != null, false);
}
/**
* Parse a location string and return a CVSRepositoryLocation.
*
* On failure, the status of the exception will be a MultiStatus
* that includes the original parsing error and a general status
* displaying the passed location and proper form. This form is
* better for logging, etc.
*/
public static CVSRepositoryLocation fromString(String location) throws CVSException {
try {
return fromString(location, false);
} catch (CVSException e) {
// Parsing failed. Include a status that
// shows the passed location and the proper form
MultiStatus error = new MultiStatus(CVSProviderPlugin.ID, IStatus.ERROR, Policy.bind("CVSRepositoryLocation.invalidFormat", new Object[] {location}), null);//$NON-NLS-1$
error.merge(new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.locationForm")));//$NON-NLS-1$
error.merge(e.getStatus());
throw new CVSException(error);
}
}
/**
* Parse a location string and return a CVSRepositoryLocation.
*
* The valid format (from the cederqvist) is:
*
* :method:[[user][:password]@]hostname[:[port]]/path/to/repository
*
* However, this does not work with CVS on NT so we use the format
*
* :method:[user[:password]@]hostname[#port]:/path/to/repository
*
* Some differences to note:
* The : after the host/port is not optional because of NT naming including device
* e.g. :pserver:username:password@hostname#port:D:\cvsroot
*
* If validateOnly is true, this method will always throw an exception.
* The status of the exception indicates success or failure. The status
* of the exception contains a specific message suitable for displaying
* to a user who has knowledge of the provided location string.
* @see CVSRepositoryLocation.fromString(String)
*/
public static CVSRepositoryLocation fromString(String location, boolean validateOnly) throws CVSException {
String partId = null;
try {
// Get the connection method
partId = "CVSRepositoryLocation.parsingMethod";//$NON-NLS-1$
int start = location.indexOf(COLON);
String methodName;
int end;
if (start == 0) {
end = location.indexOf(COLON, start + 1);
methodName = location.substring(start + 1, end);
start = end + 1;
} else {
// this could be an alternate format for ext: username:password@host:path
methodName = "ext"; //$NON-NLS-1$
start = 0;
}
IConnectionMethod method = getPluggedInConnectionMethod(methodName);
if (method == null)
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.methods", new Object[] {getPluggedInConnectionMethodNames()})));//$NON-NLS-1$
// Get the user name and password (if provided)
partId = "CVSRepositoryLocation.parsingUser";//$NON-NLS-1$
- end = location.lastIndexOf(HOST_SEPARATOR, start);
+ end = location.lastIndexOf(HOST_SEPARATOR);
String user = null;
String password = null;
// if end is -1 then there is no host separator meaning that the username is not present
if (end != -1) {
// Get the optional user and password
user = location.substring(start, end);
// Separate the user and password (if there is a password)
start = user.indexOf(COLON);
if (start != -1) {
partId = "CVSRepositoryLocation.parsingPassword";//$NON-NLS-1$
password = user.substring(start+1);
user = user.substring(0, start);
}
// Set start to point after the host separator
start = end + 1;
}
// Get the host (and port)
partId = "CVSRepositoryLocation.parsingHost";//$NON-NLS-1$
end= location.indexOf(COLON, start);
String host = location.substring(start, end);
int port = USE_DEFAULT_PORT;
// Separate the port and host if there is a port
start = host.indexOf(PORT_SEPARATOR);
if (start != -1) {
// Initially, we used a # between the host and port
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
port = Integer.parseInt(host.substring(start+1));
host = host.substring(0, start);
} else {
// In the correct CVS format, the port follows the COLON
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
int index = end;
char c = location.charAt(++index);
String portString = new String();
while (Character.isDigit(c)) {
portString += c;
c = location.charAt(++index);
}
if (portString.length() > 0) {
end = index - 1;
port = Integer.parseInt(portString);
}
}
// Get the repository path (translating backslashes to slashes)
partId = "CVSRepositoryLocation.parsingRoot";//$NON-NLS-1$
start = end + 1;
String root = location.substring(start).replace('\\', '/');
if (validateOnly)
throw new CVSException(new CVSStatus(IStatus.OK, Policy.bind("ok")));//$NON-NLS-1$
return new CVSRepositoryLocation(method, user, password, host, port, root, null /* encoding */, (user != null), (password != null));
}
catch (IndexOutOfBoundsException e) {
// We'll get here if anything funny happened while extracting substrings
throw new CVSException(Policy.bind(partId));
}
catch (NumberFormatException e) {
// We'll get here if we couldn't parse a number
throw new CVSException(Policy.bind(partId));
}
}
/**
* Validate that the given string could be used to succesfully create
* a CVS repository location
*
* This method performs some initial checks to provide displayable
* feedback and also tries a more in-depth parse using
* <code>fromString(String, boolean)</code>.
*/
public static IStatus validate(String location) {
// Check some simple things that are not checked in creation
if (location == null)
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.nullLocation"));//$NON-NLS-1$
if (location.equals(""))//$NON-NLS-1$
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.emptyLocation"));//$NON-NLS-1$
if (location.endsWith(" ") || location.endsWith("\t"))//$NON-NLS-1$ //$NON-NLS-2$
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.endWhitespace"));//$NON-NLS-1$
if (!location.startsWith(":") || location.indexOf(COLON, 1) == -1)//$NON-NLS-1$
return new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.startOfLocation"));//$NON-NLS-1$
// Do some quick checks to provide geberal feedback
String formatError = Policy.bind("CVSRepositoryLocation.locationForm");//$NON-NLS-1$
int secondColon = location.indexOf(COLON, 1);
int at = location.lastIndexOf(HOST_SEPARATOR);
if (at != -1) {
String user = location.substring(secondColon + 1, at);
if (user.equals(""))//$NON-NLS-1$
return new CVSStatus(IStatus.ERROR, formatError);
} else
at = secondColon;
int colon = location.indexOf(COLON, at + 1);
if (colon == -1)
return new CVSStatus(IStatus.ERROR, formatError);
String host = location.substring(at + 1, colon);
if (host.equals(""))//$NON-NLS-1$
return new CVSStatus(IStatus.ERROR, formatError);
String path = location.substring(colon + 1, location.length());
if (path.equals(""))//$NON-NLS-1$
return new CVSStatus(IStatus.ERROR, formatError);
// Do a full parse and see if it passes
try {
fromString(location, true);
} catch (CVSException e) {
// An exception is always throw. Return the status
return e.getStatus();
}
// Looks ok (we'll actually never get here because above
// fromString(String, boolean) will always throw an exception).
return Status.OK_STATUS;
}
/**
* Get the plugged-in user authenticator if there is one.
* @return the plugged-in user authenticator or <code>null</code>
*/
public static IUserAuthenticator getAuthenticator() {
if (authenticator == null) {
authenticator = getPluggedInAuthenticator();
}
return authenticator;
}
/**
* Return the list of plugged-in connection methods.
* @return the list of plugged-in connection methods
*/
public static IConnectionMethod[] getPluggedInConnectionMethods() {
if(pluggedInConnectionMethods==null) {
List connectionMethods = new ArrayList();
if (STANDALONE_MODE) {
connectionMethods.add(new PServerConnectionMethod());
} else {
IExtension[] extensions = Platform.getPluginRegistry().getExtensionPoint(CVSProviderPlugin.ID, CVSProviderPlugin.PT_CONNECTIONMETHODS).getExtensions();
for(int i=0; i<extensions.length; i++) {
IExtension extension = extensions[i];
IConfigurationElement[] configs = extension.getConfigurationElements();
if (configs.length == 0) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSProviderPlugin.execProblem"), null);//$NON-NLS-1$
continue;
}
try {
IConfigurationElement config = configs[0];
connectionMethods.add(config.createExecutableExtension("run"));//$NON-NLS-1$
} catch (CoreException ex) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSProviderPlugin.execProblem"), ex);//$NON-NLS-1$
}
}
}
pluggedInConnectionMethods = (IConnectionMethod[])connectionMethods.toArray(new IConnectionMethod[0]);
}
return pluggedInConnectionMethods;
}
/*
* Return the connection method registered for the given name
* or <code>null</code> if none is registered with the given name.
*/
private static IConnectionMethod getPluggedInConnectionMethod(String methodName) {
Assert.isNotNull(methodName);
IConnectionMethod[] methods = getPluggedInConnectionMethods();
for(int i=0; i<methods.length; i++) {
if(methodName.equals(methods[i].getName()))
return methods[i];
}
return null;
}
/*
* Return a string containing a list of all connection methods
* that is suitable for inclusion in an error message.
*/
private static String getPluggedInConnectionMethodNames() {
IConnectionMethod[] methods = getPluggedInConnectionMethods();
StringBuffer methodNames = new StringBuffer();
for(int i=0; i<methods.length; i++) {
String name = methods[i].getName();
if (i>0)
methodNames.append(", ");//$NON-NLS-1$
methodNames.append(name);
}
return methodNames.toString();
}
/*
* Get the pluged-in authenticator from the plugin manifest.
*/
private static IUserAuthenticator getPluggedInAuthenticator() {
IExtension[] extensions = Platform.getPluginRegistry().getExtensionPoint(CVSProviderPlugin.ID, CVSProviderPlugin.PT_AUTHENTICATOR).getExtensions();
if (extensions.length == 0)
return null;
IExtension extension = extensions[0];
IConfigurationElement[] configs = extension.getConfigurationElements();
if (configs.length == 0) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSAdapter.noConfigurationElement", new Object[] {extension.getUniqueIdentifier()}), null);//$NON-NLS-1$
return null;
}
try {
IConfigurationElement config = configs[0];
return (IUserAuthenticator) config.createExecutableExtension("run");//$NON-NLS-1$
} catch (CoreException ex) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSAdapter.unableToInstantiate", new Object[] {extension.getUniqueIdentifier()}), ex);//$NON-NLS-1$
return null;
}
}
/*
* Create a CVSRepositoryLocation from its composite parts.
*/
private CVSRepositoryLocation(IConnectionMethod method, String user, String password, String host, int port, String root, String encoding, boolean userFixed, boolean passwordFixed) {
this.method = method;
this.user = user;
this.password = password;
this.host = host;
this.port = port;
this.root = root;
// The username can be fixed only if one is provided
if (userFixed && (user != null))
this.userFixed = true;
// The password can only be fixed if the username is and a password is provided
if (userFixed && passwordFixed && (password != null))
this.passwordFixed = true;
if (encoding != null) {
setEncoding(encoding);
}
}
/*
* Create the connection to the remote server.
* If anything fails, an exception will be thrown and must
* be handled by the caller.
*/
private Connection createConnection(String password, IProgressMonitor monitor) throws CVSException {
IConnectionMethod methodToUse = method;
if (method.getName().equals("ext") && extProxy != null && !extProxy.equals(method.getName())) { //$NON-NLS-1$
methodToUse = getPluggedInConnectionMethod(extProxy);
}
Connection connection = new Connection(this, methodToUse.createConnection(this, password));
connection.open(monitor);
return connection;
}
/*
* Dispose of the receiver by clearing any cached authorization information.
* This method shold only be invoked when the corresponding adapter is shut
* down or a connection is being validated.
*/
public void dispose() {
flushCache();
try {
if (hasPreferences()) {
internalGetPreferences().removeNode();
getParentPreferences().flush();
}
} catch (BackingStoreException e) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.73", getLocation(true)), e); //$NON-NLS-1$
}
}
/*
* Flush the keyring entry associated with the receiver
*/
private void flushCache() {
try {
Platform.flushAuthorizationInfo(FAKE_URL, getLocation(), AUTH_SCHEME);
} catch (CoreException e) {
// No need to report this since the location is
// most likely being disposed.
// Just fail silently and continue
CVSProviderPlugin.log(e);
}
}
/*
* @see ICVSRepositoryLocation#getHost()
*/
public String getHost() {
return host;
}
/*
* @see IRepositoryLocation#getLocation()
*
* The username is included if it is fixed.
* The password is never included even if it is fixed.
* The port is included if it is not the default port.
*/
public String getLocation() {
return getLocation(false);
}
public String getLocation(boolean forDisplay) {
return COLON + method.getName() + COLON +
(userFixed?(user +
((passwordFixed && !forDisplay)?(COLON + password):"")//$NON-NLS-1$
+ HOST_SEPARATOR):"") +//$NON-NLS-1$
host + COLON +
((port == USE_DEFAULT_PORT)?"":(new Integer(port).toString())) + //$NON-NLS-1$
root;
}
/*
* @see ICVSRepositoryLocation#getMethod()
*/
public IConnectionMethod getMethod() {
return method;
}
public boolean setMethod(String methodName) {
IConnectionMethod newMethod = getPluggedInConnectionMethod(methodName);
if (newMethod == null)
return false;
method = newMethod;
return true;
}
/*
* @see ICVSRepositoryLocation#getPort()
*/
public int getPort() {
return port;
}
/*
* @see ICVSRepositoryLocation#getEncoding()
*/
public String getEncoding() {
if (hasPreferences()) {
return internalGetPreferences().get(PREF_SERVER_ENCODING, getDefaultEncoding());
} else {
return getDefaultEncoding();
}
}
/*
* @see ICVSRepositoryLocation#setEncoding()
*/
public void setEncoding(String encoding) {
if (encoding == null || encoding == getDefaultEncoding()) {
if (hasPreferences()) {
internalGetPreferences().remove(PREF_SERVER_ENCODING);
}
} else {
ensurePreferencesStored();
internalGetPreferences().put(PREF_SERVER_ENCODING, encoding);
flushPreferences();
}
}
/*
* @see ICVSRepositoryLocation#members(CVSTag, boolean, IProgressMonitor)
*/
public ICVSRemoteResource[] members(CVSTag tag, boolean modules, IProgressMonitor progress) throws CVSException {
try {
if (modules) {
return RemoteModule.getRemoteModules(this, tag, progress);
} else {
RemoteFolder root = new RemoteFolder(null, this, ICVSRemoteFolder.REPOSITORY_ROOT_FOLDER_NAME, tag);
ICVSRemoteResource[] resources = root.members(progress);
// There is the off chance that there is a file in the root of the repository.
// This is not supported by cvs so we need to make sure there are no files
List folders = new ArrayList(resources.length);
for (int i = 0; i < resources.length; i++) {
ICVSRemoteResource remoteResource = resources[i];
if (remoteResource.isContainer()) {
folders.add(remoteResource);
}
}
return (ICVSRemoteResource[]) folders.toArray(new ICVSRemoteResource[folders.size()]);
}
} catch(TeamException e) {
throw new CVSException(e.getStatus());
}
}
/*
* @see ICVSRepositoryLocation#getRemoteFolder(String, CVSTag)
*/
public ICVSRemoteFolder getRemoteFolder(String remotePath, CVSTag tag) {
return new RemoteFolder(null, this, remotePath, tag);
}
/*
* @see ICVSRepositoryLocation#getRemoteFile(String, CVSTag)
*/
public ICVSRemoteFile getRemoteFile(String remotePath, CVSTag tag) {
IPath path = new Path(remotePath);
RemoteFolderTree remoteFolder = new RemoteFolderTree(null, this, path.removeLastSegments(1).toString(), tag);
RemoteFile remoteFile = new RemoteFile(remoteFolder, Update.STATE_ADDED_LOCAL, path.lastSegment(), null, null, tag);
remoteFolder.setChildren(new ICVSRemoteResource[] { remoteFile });
return remoteFile;
}
/*
* @see ICVSRepositoryLocation#getRootDirectory()
*/
public String getRootDirectory() {
return root;
}
/*
* @see ICVSRepositoryLocation#getTimeout()
*
* For the time being, the timeout value is a system wide value
* associated with the CVSPlugin singleton.
*/
public int getTimeout() {
return CVSProviderPlugin.getPlugin().getTimeout();
}
/*
* @see ICVSRepositoryLocation#getUserInfo()
*/
public IUserInfo getUserInfo(boolean makeUsernameMutable) {
return new UserInfo(getUsername(), password, makeUsernameMutable ? true : isUsernameMutable());
}
/*
* @see ICVSRepositoryLocation#getUsername()
* @see IUserInfo#getUsername()
*/
public String getUsername() {
// If the username is mutable, get it from the cache if it's there
if (user == null && isUsernameMutable()) {
retrievePassword();
}
return user == null ? "" : user; //$NON-NLS-1$
}
/*
* @see IUserInfo#isUsernameMutable()
*/
public boolean isUsernameMutable() {
return !userFixed;
}
/*
* Open a connection to the repository represented by the receiver.
* If the username or password are not fixed, openConnection will
* use the plugged-in authenticator to prompt for the username and/or
* password if one has not previously been provided or if the previously
* supplied username and password are invalid.
*
* This method is synchronized to ensure that authentication with the
* remote server is serialized. This is needed to avoid the situation where
* multiple failed authentications occur and result in the remote account
* being locked. The CVSProviderPlugin enforces that there is one instance
* of a CVSRepositoryLocation per remote location thus this method is called
* for any connection made to this remote location.
*/
public Connection openConnection(IProgressMonitor monitor) throws CVSException {
Object hostLock;
synchronized(hostLocks) {
hostLock = hostLocks.get(getHost());
if (hostLock == null) {
hostLock = new Object();
hostLocks.put(getHost(), hostLock);
}
}
synchronized(hostLock) {
try {
// Allow two ticks in case of a retry
monitor.beginTask(Policy.bind("CVSRepositoryLocation.openingConnection", getHost()), 2);//$NON-NLS-1$
// If we have a username and password, use them to attempt a connection
if ((user != null) && (password != null)) {
return createConnection(password, monitor);
}
// Get the repository in order to ensure that the location is known by CVS.
// (The get will record the location if it's not already recorded.
if (!KnownRepositories.getInstance().isKnownRepository(getLocation())) {
KnownRepositories.getInstance().addRepository(this, true /* broadcast */);
}
while (true) {
try {
// The following will throw an exception if authentication fails
String password = this.password;
if (password == null) {
// If the instance has no password, obtain it from the cache
password = retrievePassword();
}
if (user == null) {
// This is possible if the cache was cleared somehow for a location with a mutable username
throw new CVSAuthenticationException(new CVSStatus(IStatus.ERROR, CVSAuthenticationException.RETRY, Policy.bind("CVSRepositoryLocation.usernameRequired"))); //$NON-NLS-1$
}
if (password == null)
password = "";//$NON-NLS-1$
return createConnection(password, monitor);
} catch (CVSAuthenticationException ex) {
if (ex.getStatus().getCode() == CVSAuthenticationException.RETRY) {
String message = ex.getMessage();
IUserAuthenticator authenticator = getAuthenticator();
if (authenticator == null) {
throw new CVSAuthenticationException(Policy.bind("Client.noAuthenticator"), CVSAuthenticationException.NO_RETRY);//$NON-NLS-1$
}
authenticator.promptForUserInfo(this, this, message);
} else {
throw ex;
}
}
}
} finally {
monitor.done();
}
}
}
/*
* Implementation of inherited toString()
*/
public String toString() {
return getLocation(true);
}
public boolean equals(Object o) {
if (!(o instanceof CVSRepositoryLocation)) return false;
return getLocation().equals(((CVSRepositoryLocation)o).getLocation());
}
public int hashCode() {
return getLocation().hashCode();
}
/*
* Return the cached password from the keyring.
* Also, set the username of the receiver if the username is mutable
*/
private String retrievePassword() {
Map map = Platform.getAuthorizationInfo(FAKE_URL, getLocation(), AUTH_SCHEME);
if (map != null) {
String username = (String) map.get(INFO_USERNAME);
if (username != null && isUsernameMutable())
setUsername(username);
String password = (String) map.get(INFO_PASSWORD);
if (password != null) {
return password;
}
}
return null;
}
/*
* @see IUserInfo#setPassword(String)
*/
public void setPassword(String password) {
if (passwordFixed)
throw new UnsupportedOperationException();
// We set the password here but it will be cleared
// if the user info is cached using updateCache()
this.password = password;
}
public void setUserInfo(IUserInfo userinfo) {
user = userinfo.getUsername();
password = ((UserInfo)userinfo).getPassword();
}
/*
* @see IUserInfo#setUsername(String)
*/
public void setUsername(String user) {
if (userFixed)
throw new UnsupportedOperationException();
this.user = user;
}
public void setUserMuteable(boolean muteable) {
userFixed = !muteable;
}
public void setAllowCaching(boolean value) {
allowCaching = value;
updateCache();
}
public void updateCache() {
// Nothing to cache if the password is fixed
if (passwordFixed || ! allowCaching) return;
// Nothing to cache if the password is null and the user is fixed
if (password == null && userFixed) return;
if (updateCache(user, password)) {
// If the cache was updated, null the password field
// so we will obtain the password from the cache when needed
password = null;
}
ensurePreferencesStored();
}
/*
* Cache the user info in the keyring. Return true if the operation
* succeeded and false otherwise. If an error occurs, it will be logged.
*/
private boolean updateCache(String username, String password) {
// put the password into the Platform map
Map map = Platform.getAuthorizationInfo(FAKE_URL, getLocation(), AUTH_SCHEME);
if (map == null) {
map = new java.util.HashMap(10);
}
if (username != null)
map.put(INFO_USERNAME, username);
if (password != null)
map.put(INFO_PASSWORD, password);
try {
Platform.addAuthorizationInfo(FAKE_URL, getLocation(), AUTH_SCHEME, map);
} catch (CoreException e) {
// We should probably wrap the CoreException here!
CVSProviderPlugin.log(e);
return false;
}
return true;
}
/*
* Validate that the receiver contains valid information for
* making a connection. If the receiver contains valid
* information, the method returns. Otherwise, an exception
* indicating the problem is throw.
*/
public void validateConnection(IProgressMonitor monitor) throws CVSException {
try {
monitor = Policy.monitorFor(monitor);
monitor.beginTask(null, 100);
ICVSFolder root = CVSWorkspaceRoot.getCVSFolderFor(ResourcesPlugin.getWorkspace().getRoot());
Session session = new Session(this, root, false /* output to console */);
session.open(Policy.subMonitorFor(monitor, 50), false /* read-only */);
try {
IStatus status = Command.VERSION.execute(session, this, Policy.subMonitorFor(monitor, 50));
// Log any non-ok status
if (! status.isOK()) {
CVSProviderPlugin.log(status);
}
} finally {
session.close();
monitor.done();
}
if (getServerPlatform() == CVSNT_SERVER) {
// check for the use of a repository prefix
if (getRootDirectory().startsWith(Session.SERVER_SEPARATOR)) {
// A prefix is in use. Log a warning
CVSProviderPlugin.log(IStatus.WARNING, Policy.bind("CVSRepositoryLocation.cvsntPrefix", getLocation()), null); //$NON-NLS-1$
throw new CVSAuthenticationException(new Status(IStatus.WARNING, CVSProviderPlugin.ID, 0,
Policy.bind("CVSRepositoryLocation.cvsntPrefix", getLocation()), null)); //$NON-NLS-1$
}
}
} catch (CVSException e) {
// If the validation failed, dispose of any cached info
dispose();
throw e;
}
}
/**
* Return the server platform type. It will be one of the following:
* UNDETERMINED_PLATFORM: The platform has not been determined
* CVS_SERVER: The platform is regular CVS server
* CVSNT_SERVER: The platform in CVSNT
* If UNDETERMINED_PLATFORM is returned, the platform can be determined
* using the Command.VERSION command.
*/
public int getServerPlatform() {
return serverPlatform;
}
/**
* This method is called from Command.VERSION to set the platform type.
*/
public void setServerPlaform(IStatus status) {
// OK means that its a regular cvs server
if (status.isOK()) {
serverPlatform = CVS_SERVER;
return;
}
// Find the status that reports the CVS platform
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
IStatus iStatus = children[i];
if (iStatus.getCode() == CVSStatus.SERVER_IS_CVSNT
|| iStatus.getCode() == CVSStatus.UNSUPPORTED_SERVER_VERSION
|| iStatus.getCode() == CVSStatus.SERVER_IS_UNKNOWN) {
status = iStatus;
break;
}
}
}
// Second, check the code of the status itself to see if it is NT
switch (status.getCode()) {
case CVSStatus.SERVER_IS_CVSNT:
serverPlatform = CVSNT_SERVER;
break;
case CVSStatus.UNSUPPORTED_SERVER_VERSION:
serverPlatform = UNSUPPORTED_SERVER;
break;
case CVSStatus.SERVER_IS_UNKNOWN:
serverPlatform = UNKNOWN_SERVER;
break;
default:
// We had an error status with no info about the server.
// Mark it as undetermined.
serverPlatform = UNDETERMINED_PLATFORM;
}
}
/**
* @see ICVSRepositoryLocation#flushUserInfo()
*/
public void flushUserInfo() {
flushCache();
}
/*
* Return the command string that is to be used by the EXT connection method.
*/
String[] getExtCommand(String password) throws IOException {
// Get the user specified connection parameters
String CVS_RSH = CVSProviderPlugin.getPlugin().getCvsRshCommand();
String CVS_RSH_PARAMETERS = CVSProviderPlugin.getPlugin().getCvsRshParameters();
String CVS_SERVER = CVSProviderPlugin.getPlugin().getCvsServer();
if(CVS_RSH == null || CVS_SERVER == null) {
throw new IOException(Policy.bind("EXTServerConnection.varsNotSet")); //$NON-NLS-1$
}
// If there is only one token, assume it is the command and use the default parameters and order
if (CVS_RSH_PARAMETERS == null || CVS_RSH_PARAMETERS.length() == 0) {
if (port != USE_DEFAULT_PORT)
throw new IOException(Policy.bind("EXTServerConnection.invalidPort")); //$NON-NLS-1$
return new String[] {CVS_RSH, host, "-l", user, CVS_SERVER, INVOKE_SVR_CMD}; //$NON-NLS-1$
}
// Substitute any variables for their appropriate values
CVS_RSH_PARAMETERS = stringReplace(CVS_RSH_PARAMETERS, USER_VARIABLE, user);
CVS_RSH_PARAMETERS = stringReplace(CVS_RSH_PARAMETERS, PASSWORD_VARIABLE, password);
CVS_RSH_PARAMETERS = stringReplace(CVS_RSH_PARAMETERS, HOST_VARIABLE, host);
CVS_RSH_PARAMETERS = stringReplace(CVS_RSH_PARAMETERS, PORT_VARIABLE, new Integer(port).toString());
// Build the command list to be sent to the OS.
List commands = new ArrayList();
commands.add(CVS_RSH);
StringTokenizer tokenizer = new StringTokenizer(CVS_RSH_PARAMETERS);
while (tokenizer.hasMoreTokens()) {
String next = tokenizer.nextToken();
commands.add(next);
}
commands.add(CVS_SERVER);
commands.add(INVOKE_SVR_CMD);
return (String[]) commands.toArray(new String[commands.size()]);
}
/*
* Replace all occurances of oldString with newString
*/
private String stringReplace(String string, String oldString, String newString) {
int index = string.toLowerCase().indexOf(oldString);
if (index == -1) return string;
return stringReplace(
string.substring(0, index) + newString + string.substring(index + oldString.length()),
oldString, newString);
}
/**
* Return the server message with the prefix removed.
* Server aborted messages typically start with
* "cvs server: ..."
* "cvs [server aborted]: ..."
* "cvs rtag: ..."
*/
public String getServerMessageWithoutPrefix(String errorLine, String prefix) {
String message = errorLine;
int firstSpace = message.indexOf(' ');
if(firstSpace != -1) {
// remove the program name and the space
message = message.substring(firstSpace + 1);
// Quick fix to handle changes in server message format (see Bug 45138)
if (prefix.startsWith("[")) { //$NON-NLS-1$
// This is the server aborted message
// Remove the pattern "[command_name aborted]: "
int closingBracket = message.indexOf("]: "); //$NON-NLS-1$
if (closingBracket == -1) return null;
// get what is inside the brackets
String realPrefix = message.substring(1, closingBracket);
// check that there is two words and the second word is "aborted"
int space = realPrefix.indexOf(' ');
if (space == -1) return null;
if (realPrefix.indexOf(' ', space +1) != -1) return null;
if (!realPrefix.substring(space +1).equals("aborted")) return null; //$NON-NLS-1$
// It's a match, return the rest of the line
message = message.substring(closingBracket + 2);
if (message.charAt(0) == ' ') {
message = message.substring(1);
}
return message;
} else {
// This is the server command message
// Remove the pattern "command_name: "
int colon = message.indexOf(": "); //$NON-NLS-1$
if (colon == -1) return null;
// get what is before the colon
String realPrefix = message.substring(0, colon);
// ensure that it is a single word
if (realPrefix.indexOf(' ') != -1) return null;
message = message.substring(colon + 1);
if (message.charAt(0) == ' ') {
message = message.substring(1);
}
return message;
}
}
// This is not a server message with the desired prefix
return null;
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation#getUserAuthenticator()
*/
public IUserAuthenticator getUserAuthenticator() {
return getAuthenticator();
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation#setUserAuthenticator()
*/
public void setUserAuthenticator(IUserAuthenticator authenticator) {
CVSRepositoryLocation.authenticator = authenticator;
}
/*
* Return the preferences node for this repository
*/
public Preferences getPreferences() {
if (!hasPreferences()) {
ensurePreferencesStored();
}
return internalGetPreferences();
}
private Preferences internalGetPreferences() {
return getParentPreferences().node(getPreferenceName());
}
private boolean hasPreferences() {
try {
return getParentPreferences().nodeExists(getPreferenceName());
} catch (BackingStoreException e) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.74", getLocation(true)), e); //$NON-NLS-1$
return false;
}
}
/**
* Return a unique name that identifies this location but
* does not contain any slashes (/). Also, do not use ':'.
* Although a valid path character, the initial core implementation
* didn't handle it well.
*/
private String getPreferenceName() {
return getLocation().replace('/', '%').replace(':', '%');
}
public void storePreferences() {
Preferences prefs = internalGetPreferences();
// Must store at least one preference in the node
prefs.put(PREF_LOCATION, getLocation());
flushPreferences();
}
private void flushPreferences() {
try {
internalGetPreferences().flush();
} catch (BackingStoreException e) {
CVSProviderPlugin.log(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.75", getLocation(true)), e); //$NON-NLS-1$
}
}
private void ensurePreferencesStored() {
if (!hasPreferences()) {
storePreferences();
}
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation#getUserInfoCached()
*/
public boolean getUserInfoCached() {
Map map = Platform.getAuthorizationInfo(FAKE_URL, getLocation(), AUTH_SCHEME);
if (map != null) {
String password = (String) map.get(INFO_PASSWORD);
return (password != null);
}
return false;
}
}
| true | true | public static CVSRepositoryLocation fromString(String location, boolean validateOnly) throws CVSException {
String partId = null;
try {
// Get the connection method
partId = "CVSRepositoryLocation.parsingMethod";//$NON-NLS-1$
int start = location.indexOf(COLON);
String methodName;
int end;
if (start == 0) {
end = location.indexOf(COLON, start + 1);
methodName = location.substring(start + 1, end);
start = end + 1;
} else {
// this could be an alternate format for ext: username:password@host:path
methodName = "ext"; //$NON-NLS-1$
start = 0;
}
IConnectionMethod method = getPluggedInConnectionMethod(methodName);
if (method == null)
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.methods", new Object[] {getPluggedInConnectionMethodNames()})));//$NON-NLS-1$
// Get the user name and password (if provided)
partId = "CVSRepositoryLocation.parsingUser";//$NON-NLS-1$
end = location.lastIndexOf(HOST_SEPARATOR, start);
String user = null;
String password = null;
// if end is -1 then there is no host separator meaning that the username is not present
if (end != -1) {
// Get the optional user and password
user = location.substring(start, end);
// Separate the user and password (if there is a password)
start = user.indexOf(COLON);
if (start != -1) {
partId = "CVSRepositoryLocation.parsingPassword";//$NON-NLS-1$
password = user.substring(start+1);
user = user.substring(0, start);
}
// Set start to point after the host separator
start = end + 1;
}
// Get the host (and port)
partId = "CVSRepositoryLocation.parsingHost";//$NON-NLS-1$
end= location.indexOf(COLON, start);
String host = location.substring(start, end);
int port = USE_DEFAULT_PORT;
// Separate the port and host if there is a port
start = host.indexOf(PORT_SEPARATOR);
if (start != -1) {
// Initially, we used a # between the host and port
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
port = Integer.parseInt(host.substring(start+1));
host = host.substring(0, start);
} else {
// In the correct CVS format, the port follows the COLON
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
int index = end;
char c = location.charAt(++index);
String portString = new String();
while (Character.isDigit(c)) {
portString += c;
c = location.charAt(++index);
}
if (portString.length() > 0) {
end = index - 1;
port = Integer.parseInt(portString);
}
}
// Get the repository path (translating backslashes to slashes)
partId = "CVSRepositoryLocation.parsingRoot";//$NON-NLS-1$
start = end + 1;
String root = location.substring(start).replace('\\', '/');
if (validateOnly)
throw new CVSException(new CVSStatus(IStatus.OK, Policy.bind("ok")));//$NON-NLS-1$
return new CVSRepositoryLocation(method, user, password, host, port, root, null /* encoding */, (user != null), (password != null));
}
catch (IndexOutOfBoundsException e) {
// We'll get here if anything funny happened while extracting substrings
throw new CVSException(Policy.bind(partId));
}
catch (NumberFormatException e) {
// We'll get here if we couldn't parse a number
throw new CVSException(Policy.bind(partId));
}
}
| public static CVSRepositoryLocation fromString(String location, boolean validateOnly) throws CVSException {
String partId = null;
try {
// Get the connection method
partId = "CVSRepositoryLocation.parsingMethod";//$NON-NLS-1$
int start = location.indexOf(COLON);
String methodName;
int end;
if (start == 0) {
end = location.indexOf(COLON, start + 1);
methodName = location.substring(start + 1, end);
start = end + 1;
} else {
// this could be an alternate format for ext: username:password@host:path
methodName = "ext"; //$NON-NLS-1$
start = 0;
}
IConnectionMethod method = getPluggedInConnectionMethod(methodName);
if (method == null)
throw new CVSException(new CVSStatus(IStatus.ERROR, Policy.bind("CVSRepositoryLocation.methods", new Object[] {getPluggedInConnectionMethodNames()})));//$NON-NLS-1$
// Get the user name and password (if provided)
partId = "CVSRepositoryLocation.parsingUser";//$NON-NLS-1$
end = location.lastIndexOf(HOST_SEPARATOR);
String user = null;
String password = null;
// if end is -1 then there is no host separator meaning that the username is not present
if (end != -1) {
// Get the optional user and password
user = location.substring(start, end);
// Separate the user and password (if there is a password)
start = user.indexOf(COLON);
if (start != -1) {
partId = "CVSRepositoryLocation.parsingPassword";//$NON-NLS-1$
password = user.substring(start+1);
user = user.substring(0, start);
}
// Set start to point after the host separator
start = end + 1;
}
// Get the host (and port)
partId = "CVSRepositoryLocation.parsingHost";//$NON-NLS-1$
end= location.indexOf(COLON, start);
String host = location.substring(start, end);
int port = USE_DEFAULT_PORT;
// Separate the port and host if there is a port
start = host.indexOf(PORT_SEPARATOR);
if (start != -1) {
// Initially, we used a # between the host and port
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
port = Integer.parseInt(host.substring(start+1));
host = host.substring(0, start);
} else {
// In the correct CVS format, the port follows the COLON
partId = "CVSRepositoryLocation.parsingPort";//$NON-NLS-1$
int index = end;
char c = location.charAt(++index);
String portString = new String();
while (Character.isDigit(c)) {
portString += c;
c = location.charAt(++index);
}
if (portString.length() > 0) {
end = index - 1;
port = Integer.parseInt(portString);
}
}
// Get the repository path (translating backslashes to slashes)
partId = "CVSRepositoryLocation.parsingRoot";//$NON-NLS-1$
start = end + 1;
String root = location.substring(start).replace('\\', '/');
if (validateOnly)
throw new CVSException(new CVSStatus(IStatus.OK, Policy.bind("ok")));//$NON-NLS-1$
return new CVSRepositoryLocation(method, user, password, host, port, root, null /* encoding */, (user != null), (password != null));
}
catch (IndexOutOfBoundsException e) {
// We'll get here if anything funny happened while extracting substrings
throw new CVSException(Policy.bind(partId));
}
catch (NumberFormatException e) {
// We'll get here if we couldn't parse a number
throw new CVSException(Policy.bind(partId));
}
}
|
diff --git a/src/main/java/nz/co/searchwellington/controllers/ResourceEditController.java b/src/main/java/nz/co/searchwellington/controllers/ResourceEditController.java
index 8534f6e9..ab8110b8 100644
--- a/src/main/java/nz/co/searchwellington/controllers/ResourceEditController.java
+++ b/src/main/java/nz/co/searchwellington/controllers/ResourceEditController.java
@@ -1,497 +1,497 @@
package nz.co.searchwellington.controllers;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nz.co.searchwellington.controllers.admin.AdminRequestFilter;
import nz.co.searchwellington.controllers.admin.EditPermissionService;
import nz.co.searchwellington.feeds.FeedItemAcceptor;
import nz.co.searchwellington.feeds.FeednewsItemToNewsitemService;
import nz.co.searchwellington.feeds.RssfeedNewsitemService;
import nz.co.searchwellington.feeds.reading.WhakaoroClientFactory;
import nz.co.searchwellington.htmlparsing.SnapshotBodyExtractor;
import nz.co.searchwellington.model.Feed;
import nz.co.searchwellington.model.FeedAcceptancePolicy;
import nz.co.searchwellington.model.Newsitem;
import nz.co.searchwellington.model.PublishedResource;
import nz.co.searchwellington.model.Resource;
import nz.co.searchwellington.model.Tag;
import nz.co.searchwellington.model.UrlWordsGenerator;
import nz.co.searchwellington.model.User;
import nz.co.searchwellington.model.mappers.FrontendResourceMapper;
import nz.co.searchwellington.modification.ContentDeletionService;
import nz.co.searchwellington.modification.ContentUpdateService;
import nz.co.searchwellington.queues.LinkCheckerQueue;
import nz.co.searchwellington.repositories.HandTaggingDAO;
import nz.co.searchwellington.repositories.ResourceFactory;
import nz.co.searchwellington.spam.SpamFilter;
import nz.co.searchwellington.tagging.AutoTaggingService;
import nz.co.searchwellington.widgets.AcceptanceWidgetFactory;
import nz.co.searchwellington.widgets.TagsWidgetFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.google.common.base.Strings;
@Controller
public class ResourceEditController {
private static Logger log = Logger.getLogger(ResourceEditController.class);
private static final String ACCEPTANCE = "acceptance";
private RssfeedNewsitemService rssfeedNewsitemService;
private AdminRequestFilter adminRequestFilter;
private TagsWidgetFactory tagWidgetFactory;
private AutoTaggingService autoTagger;
private AcceptanceWidgetFactory acceptanceWidgetFactory;
private EditPermissionService editPermissionService;
private SubmissionProcessingService submissionProcessingService;
private ContentUpdateService contentUpdateService;
private ContentDeletionService contentDeletionService;
private SnapshotBodyExtractor snapBodyExtractor;
private AnonUserService anonUserService;
private HandTaggingDAO tagVoteDAO;
private FeedItemAcceptor feedItemAcceptor;
private ResourceFactory resourceFactory;
private CommonModelObjectsService commonModelObjectsService;
private LoggedInUserFilter loggedInUserFilter;
private UrlStack urlStack;
private FeednewsItemToNewsitemService feednewsItemToNewsitemService;
private UrlWordsGenerator urlWordsGenerator;
private WhakaoroClientFactory whakaoroClientFactory;
private FrontendResourceMapper frontendResourceMapper;
private SpamFilter spamFilter;
private LinkCheckerQueue linkCheckerQueue;
public ResourceEditController() {
}
@Autowired
public ResourceEditController(
RssfeedNewsitemService rssfeedNewsitemService,
AdminRequestFilter adminRequestFilter,
TagsWidgetFactory tagWidgetFactory, AutoTaggingService autoTagger,
AcceptanceWidgetFactory acceptanceWidgetFactory,
LoggedInUserFilter loggedInUserFilter,
EditPermissionService editPermissionService, UrlStack urlStack,
SubmissionProcessingService submissionProcessingService,
ContentUpdateService contentUpdateService,
ContentDeletionService contentDeletionService,
SnapshotBodyExtractor snapBodyExtractor,
AnonUserService anonUserService,
HandTaggingDAO tagVoteDAO, FeedItemAcceptor feedItemAcceptor,
ResourceFactory resourceFactory,
CommonModelObjectsService commonModelObjectsService,
FeednewsItemToNewsitemService feednewsItemToNewsitemService,
UrlWordsGenerator urlWordsGenerator,
WhakaoroClientFactory whakaoroClientFactory,
FrontendResourceMapper frontendResourceMapper,
SpamFilter spamFilter, LinkCheckerQueue linkCheckerQueue) {
this.rssfeedNewsitemService = rssfeedNewsitemService;
this.adminRequestFilter = adminRequestFilter;
this.tagWidgetFactory = tagWidgetFactory;
this.autoTagger = autoTagger;
this.acceptanceWidgetFactory = acceptanceWidgetFactory;
this.loggedInUserFilter = loggedInUserFilter;
this.editPermissionService = editPermissionService;
this.urlStack = urlStack;
this.submissionProcessingService = submissionProcessingService;
this.contentUpdateService = contentUpdateService;
this.contentDeletionService = contentDeletionService;
this.snapBodyExtractor = snapBodyExtractor;
this.anonUserService = anonUserService;
this.tagVoteDAO = tagVoteDAO;
this.feedItemAcceptor = feedItemAcceptor;
this.resourceFactory = resourceFactory;
this.commonModelObjectsService = commonModelObjectsService;
this.feednewsItemToNewsitemService = feednewsItemToNewsitemService;
this.urlWordsGenerator = urlWordsGenerator;
this.whakaoroClientFactory = whakaoroClientFactory;
this.frontendResourceMapper = frontendResourceMapper;
this.spamFilter = spamFilter;
this.linkCheckerQueue = linkCheckerQueue;
}
@Transactional
@RequestMapping("/edit")
public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) {
log.info("Starting resource edit method");
response.setCharacterEncoding("UTF-8");
adminRequestFilter.loadAttributesOntoRequest(request);
Resource resource = (Resource) request.getAttribute("resource");
if (request.getAttribute("resource") == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
log.info("No resource attribute found on request; returning 404");
return null;
}
final User loggedInUser = loggedInUserFilter.getLoggedInUser();
if (!userIsAllowedToEdit(resource, request, loggedInUser)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
log.info("No logged in user or user not allowed to edit resource; returning 403");
return null;
}
ModelAndView mv = new ModelAndView("editResource");
commonModelObjectsService.populateCommonLocal(mv);
mv.addObject("heading", "Editing a Resource");
mv.addObject("resource", resource);
mv.addObject("tag_select", tagWidgetFactory.createMultipleTagSelect(tagVoteDAO.getHandpickedTagsForThisResourceByUser(loggedInUser, resource)));
mv.addObject("show_additional_tags", 1);
boolean userIsLoggedIn = loggedInUser != null;
populatePublisherField(mv, userIsLoggedIn, resource);
if (resource.getType().equals("F")) {
mv.addObject("acceptance_select", acceptanceWidgetFactory.createAcceptanceSelect (((Feed)resource).getAcceptancePolicy()));
}
return mv;
}
@Transactional
@RequestMapping("/edit/viewsnapshot")
public ModelAndView viewSnapshot(HttpServletRequest request, HttpServletResponse response) {
adminRequestFilter.loadAttributesOntoRequest(request);
if (request.getAttribute("resource") == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return null;
}
Resource resource = (Resource) request.getAttribute("resource");
final User loggedInUser = loggedInUserFilter.getLoggedInUser();
if (!userIsAllowedToEdit(resource, request, loggedInUser)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return null;
}
Resource editResource = (Resource) request.getAttribute("resource");
if (request.getAttribute("resource") != null && userIsAllowedToEdit(editResource, request, loggedInUser)) {
ModelAndView mv = new ModelAndView("viewSnapshot");
commonModelObjectsService.populateCommonLocal(mv);
mv.addObject("heading", "Resource snapshot");
mv.addObject("resource", editResource);
mv.addObject("body", snapBodyExtractor.extractLatestSnapshotBodyTextFor(editResource));
mv.addObject("tag_select", tagWidgetFactory.createMultipleTagSelect(tagVoteDAO.getHandpickedTagsForThisResourceByUser(loggedInUser, editResource)));
mv.addObject("show_additional_tags", 1);
return mv;
}
return new ModelAndView(new RedirectView(urlStack.getExitUrlFromStack(request)));
}
@Transactional
@RequestMapping("/edit/accept")
// TODO should be a straight delegation to the feed acceptor?
public ModelAndView accept(HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, IOException {
response.setCharacterEncoding("UTF-8");
adminRequestFilter.loadAttributesOntoRequest(request); // TODO get all admin things into a common path and then make this a web.xml filter
User loggedInUser = loggedInUserFilter.getLoggedInUser();
if (!editPermissionService.canAcceptFeedItems(loggedInUser)) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return null;
}
final String url = request.getParameter("url");
if (url == null) {
log.warn("No feeditem url given");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return null;
}
final Feed feed = (Feed) request.getAttribute("feedAttribute");
if (feed == null) {
throw new RuntimeException("Could not find feed");
}
Newsitem acceptedNewsitem = feednewsItemToNewsitemService.makeNewsitemFromFeedItem(feed, rssfeedNewsitemService.getFeedNewsitemByUrl(feed, url));
if (acceptedNewsitem == null) {
log.warn("No matching newsitem found for url: " + url);
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return null;
}
acceptedNewsitem = feedItemAcceptor.acceptFeedItem(loggedInUser, acceptedNewsitem);
final ModelAndView modelAndView = new ModelAndView("acceptResource");
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("heading", "Accepting a submission");
modelAndView.addObject("resource", acceptedNewsitem);
modelAndView.addObject("publisher_select", "1");
modelAndView.addObject("tag_select", tagWidgetFactory.createMultipleTagSelect(new HashSet<Tag>()));
modelAndView.addObject("acceptedFromFeed", urlWordsGenerator.makeUrlWordsFromName(acceptedNewsitem.getFeed() != null ? acceptedNewsitem.getFeed().getName() : null));
return modelAndView;
}
@Transactional
@RequestMapping("/edit/submit/website")
public ModelAndView submitWebsite(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("submitWebsite");
modelAndView.addObject("heading", "Submitting a Website");
Resource editResource = resourceFactory.createNewWebsite();
modelAndView.addObject("resource", editResource);
populateSubmitCommonElements(request, modelAndView);
modelAndView.addObject("publisher_select", null);
return modelAndView;
}
@Transactional
@RequestMapping("/edit/submit/newsitem")
public ModelAndView submitNewsitem(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("submitNewsitem");
modelAndView.addObject("heading", "Submitting a Newsitem");
Resource editResource = resourceFactory.createNewNewsitem();
modelAndView.addObject("resource", editResource);
populateSubmitCommonElements(request, modelAndView);
return modelAndView;
}
@Transactional
@RequestMapping("/edit/submit/calendar")
public ModelAndView submitCalendar(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("submitCalendar");
modelAndView.addObject("heading", "Submitting a Calendar");
Resource editResource = resourceFactory.createNewCalendarFeed("");
modelAndView.addObject("resource", editResource);
populateSubmitCommonElements(request, modelAndView);
return modelAndView;
}
@Transactional
@RequestMapping("/edit/submit/feed")
public ModelAndView submitFeed(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("submitFeed");
modelAndView.addObject("heading", "Submitting a Feed");
Resource editResource = resourceFactory.createNewFeed();
modelAndView.addObject("resource", editResource);
modelAndView.addObject("acceptance_select", acceptanceWidgetFactory.createAcceptanceSelect(null));
populateSubmitCommonElements(request, modelAndView);
return modelAndView;
}
@Transactional
@RequestMapping("/edit/submit/watchlist")
public ModelAndView submitWatchlist(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("submitWatchlist");
modelAndView.addObject("heading", "Submitting a Watchlist Item");
Resource editResource = resourceFactory.createNewWebsite();
modelAndView.addObject("resource", editResource);
populateSubmitCommonElements(request, modelAndView);
return modelAndView;
}
@Transactional
@RequestMapping("/delete")
public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView("deletedResource");
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("heading", "Resource Deleted");
adminRequestFilter.loadAttributesOntoRequest(request);
Resource editResource = (Resource) request.getAttribute("resource");
if (editResource != null && editPermissionService.canDelete(editResource)) {
modelAndView.addObject("resource", editResource);
editResource = (Resource) request.getAttribute("resource");
contentDeletionService.performDelete(editResource);
if (editResource.getType().equals("F")) {
urlStack.setUrlStack(request, "");
}
}
// TODO need to given failure message if we didn't actually remove the item.
return modelAndView;
}
@Transactional
@RequestMapping(value="/save", method=RequestMethod.POST)
public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
final ModelAndView modelAndView = new ModelAndView("savedResource");
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("heading", "Resource Saved");
User loggedInUser = loggedInUserFilter.getLoggedInUser();
adminRequestFilter.loadAttributesOntoRequest(request);
Resource editResource = null;
if (request.getAttribute("resource") != null) {
editResource = (Resource) request.getAttribute("resource");
} else {
log.info("Creating new resource.");
if (request.getParameter("type") != null) {
String type = request.getParameter("type");
if (type.equals("W")) {
editResource = resourceFactory.createNewWebsite();
} else if (type.equals("N")) {
editResource = resourceFactory.createNewNewsitem();
} else if (type.equals("F")) {
editResource = resourceFactory.createNewFeed();
} else if (type.equals("L")) {
editResource = resourceFactory.createNewWatchlist();
} else if (type.equals("C")) {
editResource = resourceFactory.createNewCalendarFeed("");
} else {
// TODO this should be a caught error.
editResource = resourceFactory.createNewWebsite();
}
}
}
log.info("In save");
if (editResource != null) {
boolean newSubmission = editResource.getId() == 0;
if (loggedInUser == null) {
loggedInUser = createAndSetAnonUser(request);
}
if (newSubmission) { // TODO is wrong place - needs to be shared with the api.
editResource.setOwner(loggedInUser);
}
submissionProcessingService.processUrl(request, editResource);
submissionProcessingService.processTitle(request, editResource);
editResource.setGeocode(submissionProcessingService.processGeocode(request));
submissionProcessingService.processDate(request, editResource);
submissionProcessingService.processHeld(request, editResource);
submissionProcessingService.processEmbargoDate(request, editResource);
submissionProcessingService.processDescription(request, editResource);
submissionProcessingService.processPublisher(request, editResource);
if (editResource.getType().equals("N")) {
submissionProcessingService.processImage(request, (Newsitem) editResource, loggedInUser);
submissionProcessingService.processAcceptance(request, editResource, loggedInUser);
}
if (editResource.getType().equals("W") || editResource.getType().equals("F")) {
editResource.setUrlWords(urlWordsGenerator.makeUrlWordsFromName(editResource.getName()));
}
processFeedAcceptancePolicy(request, editResource);
boolean isSpamUrl = spamFilter.isSpam(editResource);
boolean isPublicSubmission = loggedInUser == null || (loggedInUser.isUnlinkedAccount());
if (isPublicSubmission) {
log.info("This is a public submission; marking as held");
editResource.setHeld(true);
}
if (editResource.getType().equals("F") && !Strings.isNullOrEmpty(editResource.getUrl())) {
// TODO deletes and renames
String createFeedSubscription = whakaoroClientFactory.createFeedSubscription(editResource.getUrl());
((Feed) editResource).setWhakaokoId(createFeedSubscription);
}
boolean okToSave = !newSubmission || !isSpamUrl || loggedInUser != null; // TODO validate. - what exactly?
if (okToSave) {
saveResource(request, loggedInUser, editResource);
log.info("Saved resource; id is now: " + editResource.getId());
submissionProcessingService.processTags(request, editResource, loggedInUser);
if (newSubmission) {
log.info("Applying the auto tagger to new submission.");
autoTagger.autotag(editResource);
}
saveResource(request, loggedInUser, editResource); // TODO with the tags votes do sticking to an unsaved resource - transaction boundary issue?
- linkCheckerQueue.add(editResource.getId());
+ linkCheckerQueue.add(editResource.getId()); // TODO this link check fails as the queue picks up before the transaction window has closed.
} else {
log.info("Could not save resource. Spam question not answered?");
}
modelAndView.addObject("item", frontendResourceMapper.createFrontendResourceFrom(editResource));
} else {
log.warn("No edit resource could be setup.");
}
return modelAndView;
}
// TODO duplicated in public tagging
private User createAndSetAnonUser(HttpServletRequest request) {
log.info("Creating new anon user for resource submission");
final User loggedInUser = anonUserService.createAnonUser();
loggedInUserFilter.setLoggedInUser(request, loggedInUser);
loggedInUserFilter.loadLoggedInUser(request);
return loggedInUser;
}
// TODO move to submission handling service.
private void processFeedAcceptancePolicy(HttpServletRequest request, Resource editResource) {
if (editResource.getType().equals("F")) {
((Feed) editResource).setAcceptancePolicy(FeedAcceptancePolicy.IGNORE);
if (request.getParameter(ACCEPTANCE) != null) {
((Feed) editResource).setAcceptancePolicy(FeedAcceptancePolicy.valueOf(request.getParameter(ACCEPTANCE)));
log.debug("Feed acceptance policy set to: " + ((Feed) editResource).getAcceptancePolicy());
}
}
}
private void saveResource(HttpServletRequest request, User loggedInUser, Resource editResource) {
contentUpdateService.update(editResource);
}
private boolean userIsAllowedToEdit(Resource editResource, HttpServletRequest request, User loggedInUser) {
return editPermissionService.canEdit(editResource);
}
private void populateSubmitCommonElements(HttpServletRequest request, ModelAndView modelAndView) {
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("tag_select", tagWidgetFactory.createMultipleTagSelect(new HashSet<Tag>()));
User loggedInUser = loggedInUserFilter.getLoggedInUser();
boolean userIsLoggedIn = loggedInUser != null;
modelAndView.addObject("publisher_select", "1");
if (userIsLoggedIn) {
// TODO duplication - also - what does this do?
modelAndView.addObject("show_additional_tags", 1);
}
}
private void populatePublisherField(ModelAndView modelAndView, boolean userIsLoggedIn, Resource editResource) {
boolean isPublishedResource = editResource instanceof PublishedResource;
if (isPublishedResource) {
modelAndView.addObject("publisher_select", "1");
} else {
log.info("Edit resource is not a publisher resource.");
}
}
}
| true | true | public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
final ModelAndView modelAndView = new ModelAndView("savedResource");
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("heading", "Resource Saved");
User loggedInUser = loggedInUserFilter.getLoggedInUser();
adminRequestFilter.loadAttributesOntoRequest(request);
Resource editResource = null;
if (request.getAttribute("resource") != null) {
editResource = (Resource) request.getAttribute("resource");
} else {
log.info("Creating new resource.");
if (request.getParameter("type") != null) {
String type = request.getParameter("type");
if (type.equals("W")) {
editResource = resourceFactory.createNewWebsite();
} else if (type.equals("N")) {
editResource = resourceFactory.createNewNewsitem();
} else if (type.equals("F")) {
editResource = resourceFactory.createNewFeed();
} else if (type.equals("L")) {
editResource = resourceFactory.createNewWatchlist();
} else if (type.equals("C")) {
editResource = resourceFactory.createNewCalendarFeed("");
} else {
// TODO this should be a caught error.
editResource = resourceFactory.createNewWebsite();
}
}
}
log.info("In save");
if (editResource != null) {
boolean newSubmission = editResource.getId() == 0;
if (loggedInUser == null) {
loggedInUser = createAndSetAnonUser(request);
}
if (newSubmission) { // TODO is wrong place - needs to be shared with the api.
editResource.setOwner(loggedInUser);
}
submissionProcessingService.processUrl(request, editResource);
submissionProcessingService.processTitle(request, editResource);
editResource.setGeocode(submissionProcessingService.processGeocode(request));
submissionProcessingService.processDate(request, editResource);
submissionProcessingService.processHeld(request, editResource);
submissionProcessingService.processEmbargoDate(request, editResource);
submissionProcessingService.processDescription(request, editResource);
submissionProcessingService.processPublisher(request, editResource);
if (editResource.getType().equals("N")) {
submissionProcessingService.processImage(request, (Newsitem) editResource, loggedInUser);
submissionProcessingService.processAcceptance(request, editResource, loggedInUser);
}
if (editResource.getType().equals("W") || editResource.getType().equals("F")) {
editResource.setUrlWords(urlWordsGenerator.makeUrlWordsFromName(editResource.getName()));
}
processFeedAcceptancePolicy(request, editResource);
boolean isSpamUrl = spamFilter.isSpam(editResource);
boolean isPublicSubmission = loggedInUser == null || (loggedInUser.isUnlinkedAccount());
if (isPublicSubmission) {
log.info("This is a public submission; marking as held");
editResource.setHeld(true);
}
if (editResource.getType().equals("F") && !Strings.isNullOrEmpty(editResource.getUrl())) {
// TODO deletes and renames
String createFeedSubscription = whakaoroClientFactory.createFeedSubscription(editResource.getUrl());
((Feed) editResource).setWhakaokoId(createFeedSubscription);
}
boolean okToSave = !newSubmission || !isSpamUrl || loggedInUser != null; // TODO validate. - what exactly?
if (okToSave) {
saveResource(request, loggedInUser, editResource);
log.info("Saved resource; id is now: " + editResource.getId());
submissionProcessingService.processTags(request, editResource, loggedInUser);
if (newSubmission) {
log.info("Applying the auto tagger to new submission.");
autoTagger.autotag(editResource);
}
saveResource(request, loggedInUser, editResource); // TODO with the tags votes do sticking to an unsaved resource - transaction boundary issue?
linkCheckerQueue.add(editResource.getId());
} else {
log.info("Could not save resource. Spam question not answered?");
}
modelAndView.addObject("item", frontendResourceMapper.createFrontendResourceFrom(editResource));
} else {
log.warn("No edit resource could be setup.");
}
return modelAndView;
}
| public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
final ModelAndView modelAndView = new ModelAndView("savedResource");
commonModelObjectsService.populateCommonLocal(modelAndView);
modelAndView.addObject("heading", "Resource Saved");
User loggedInUser = loggedInUserFilter.getLoggedInUser();
adminRequestFilter.loadAttributesOntoRequest(request);
Resource editResource = null;
if (request.getAttribute("resource") != null) {
editResource = (Resource) request.getAttribute("resource");
} else {
log.info("Creating new resource.");
if (request.getParameter("type") != null) {
String type = request.getParameter("type");
if (type.equals("W")) {
editResource = resourceFactory.createNewWebsite();
} else if (type.equals("N")) {
editResource = resourceFactory.createNewNewsitem();
} else if (type.equals("F")) {
editResource = resourceFactory.createNewFeed();
} else if (type.equals("L")) {
editResource = resourceFactory.createNewWatchlist();
} else if (type.equals("C")) {
editResource = resourceFactory.createNewCalendarFeed("");
} else {
// TODO this should be a caught error.
editResource = resourceFactory.createNewWebsite();
}
}
}
log.info("In save");
if (editResource != null) {
boolean newSubmission = editResource.getId() == 0;
if (loggedInUser == null) {
loggedInUser = createAndSetAnonUser(request);
}
if (newSubmission) { // TODO is wrong place - needs to be shared with the api.
editResource.setOwner(loggedInUser);
}
submissionProcessingService.processUrl(request, editResource);
submissionProcessingService.processTitle(request, editResource);
editResource.setGeocode(submissionProcessingService.processGeocode(request));
submissionProcessingService.processDate(request, editResource);
submissionProcessingService.processHeld(request, editResource);
submissionProcessingService.processEmbargoDate(request, editResource);
submissionProcessingService.processDescription(request, editResource);
submissionProcessingService.processPublisher(request, editResource);
if (editResource.getType().equals("N")) {
submissionProcessingService.processImage(request, (Newsitem) editResource, loggedInUser);
submissionProcessingService.processAcceptance(request, editResource, loggedInUser);
}
if (editResource.getType().equals("W") || editResource.getType().equals("F")) {
editResource.setUrlWords(urlWordsGenerator.makeUrlWordsFromName(editResource.getName()));
}
processFeedAcceptancePolicy(request, editResource);
boolean isSpamUrl = spamFilter.isSpam(editResource);
boolean isPublicSubmission = loggedInUser == null || (loggedInUser.isUnlinkedAccount());
if (isPublicSubmission) {
log.info("This is a public submission; marking as held");
editResource.setHeld(true);
}
if (editResource.getType().equals("F") && !Strings.isNullOrEmpty(editResource.getUrl())) {
// TODO deletes and renames
String createFeedSubscription = whakaoroClientFactory.createFeedSubscription(editResource.getUrl());
((Feed) editResource).setWhakaokoId(createFeedSubscription);
}
boolean okToSave = !newSubmission || !isSpamUrl || loggedInUser != null; // TODO validate. - what exactly?
if (okToSave) {
saveResource(request, loggedInUser, editResource);
log.info("Saved resource; id is now: " + editResource.getId());
submissionProcessingService.processTags(request, editResource, loggedInUser);
if (newSubmission) {
log.info("Applying the auto tagger to new submission.");
autoTagger.autotag(editResource);
}
saveResource(request, loggedInUser, editResource); // TODO with the tags votes do sticking to an unsaved resource - transaction boundary issue?
linkCheckerQueue.add(editResource.getId()); // TODO this link check fails as the queue picks up before the transaction window has closed.
} else {
log.info("Could not save resource. Spam question not answered?");
}
modelAndView.addObject("item", frontendResourceMapper.createFrontendResourceFrom(editResource));
} else {
log.warn("No edit resource could be setup.");
}
return modelAndView;
}
|
diff --git a/src/main/java/org/atlasapi/output/simple/ItemModelSimplifier.java b/src/main/java/org/atlasapi/output/simple/ItemModelSimplifier.java
index b8407e86a..304a33acc 100644
--- a/src/main/java/org/atlasapi/output/simple/ItemModelSimplifier.java
+++ b/src/main/java/org/atlasapi/output/simple/ItemModelSimplifier.java
@@ -1,430 +1,431 @@
package org.atlasapi.output.simple;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.atlasapi.application.ApplicationConfiguration;
import org.atlasapi.media.entity.Broadcast;
import org.atlasapi.media.entity.Certificate;
import org.atlasapi.media.entity.CrewMember;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.EntityType;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Film;
import org.atlasapi.media.entity.Item;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.ParentRef;
import org.atlasapi.media.entity.Policy;
import org.atlasapi.media.entity.ReleaseDate;
import org.atlasapi.media.entity.Subtitles;
import org.atlasapi.media.entity.Version;
import org.atlasapi.media.entity.simple.BrandSummary;
import org.atlasapi.media.entity.simple.Language;
import org.atlasapi.media.entity.simple.Restriction;
import org.atlasapi.media.entity.simple.SeriesSummary;
import org.atlasapi.media.product.ProductResolver;
import org.atlasapi.media.segment.SegmentResolver;
import org.atlasapi.output.Annotation;
import org.atlasapi.persistence.output.ContainerSummaryResolver;
import org.atlasapi.persistence.topic.TopicQueryResolver;
import org.joda.time.DateTime;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSet.Builder;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.metabroadcast.common.intl.Countries;
import com.metabroadcast.common.time.Clock;
import com.metabroadcast.common.time.DateTimeZones;
import com.metabroadcast.common.time.SystemClock;
import org.atlasapi.media.entity.Song;
public class ItemModelSimplifier extends ContentModelSimplifier<Item, org.atlasapi.media.entity.simple.Item> {
private final ContainerSummaryResolver containerSummaryResolver;
private final Clock clock;
private final SegmentModelSimplifier segmentSimplifier;
private final Map<String, Locale> localeMap;
protected final CrewMemberSimplifier crewSimplifier = new CrewMemberSimplifier();
public ItemModelSimplifier(String localHostName, TopicQueryResolver topicResolver, ProductResolver productResolver, SegmentResolver segmentResolver, ContainerSummaryResolver containerSummaryResolver){
this(localHostName, topicResolver, productResolver, segmentResolver, containerSummaryResolver, new SystemClock());
}
public ItemModelSimplifier(String localHostName, TopicQueryResolver topicResolver, ProductResolver productResolver, SegmentResolver segmentResolver, ContainerSummaryResolver containerSummaryResolver, Clock clock) {
super(localHostName, topicResolver, productResolver);
this.containerSummaryResolver = containerSummaryResolver;
this.clock = clock;
this.segmentSimplifier = segmentResolver != null ? new SegmentModelSimplifier(segmentResolver) : null;
this.localeMap = initLocalMap();
}
private Map<String,Locale> initLocalMap() {
ImmutableMap.Builder<String, Locale> builder = ImmutableMap.builder();
for (String code : Locale.getISOLanguages()) {
builder.put(code, new Locale(code));
}
return builder.build();
}
@Override
public org.atlasapi.media.entity.simple.Item simplify(Item full, final Set<Annotation> annotations, final ApplicationConfiguration config) {
org.atlasapi.media.entity.simple.Item simple = new org.atlasapi.media.entity.simple.Item();
copyProperties(full, simple, annotations, config);
boolean doneSegments = false;
for (Version version : full.getVersions()) {
addTo(simple, version, full, annotations);
if(!doneSegments && !version.getSegmentEvents().isEmpty() && annotations.contains(Annotation.SEGMENT_EVENTS) && segmentSimplifier != null) {
simple.setSegments(segmentSimplifier.simplify(version.getSegmentEvents(), annotations, config));
doneSegments = true;
}
}
if (annotations.contains(Annotation.PEOPLE)) {
simple.setPeople(Iterables.filter(Iterables.transform(full.people(), new Function<CrewMember, org.atlasapi.media.entity.simple.Person>() {
@Override
public org.atlasapi.media.entity.simple.Person apply(CrewMember input) {
return crewSimplifier.simplify(input, annotations, config);
}
}), Predicates.notNull()));
}
return simple;
}
private void copyProperties(Item fullItem, org.atlasapi.media.entity.simple.Item simpleItem, Set<Annotation> annotations, ApplicationConfiguration config) {
copyBasicContentAttributes(fullItem, simpleItem, annotations, config);
simpleItem.setType(EntityType.from(fullItem).toString());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setBlackAndWhite(fullItem.getBlackAndWhite());
simpleItem.setCountriesOfOrigin(fullItem.getCountriesOfOrigin());
simpleItem.setScheduleOnly(fullItem.isScheduleOnly());
}
if (fullItem.getContainer() != null) {
simpleItem.setBrandSummary(summaryFromResolved(fullItem.getContainer(), annotations));
}
if (fullItem instanceof Episode) {
Episode episode = (Episode) fullItem;
if (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION) || annotations.contains(Annotation.SERIES_SUMMARY)) {
ParentRef series = episode.getSeriesRef();
if (series != null) {
simpleItem.setSeriesSummary(seriesSummaryFromResolved(series, annotations));
}
}
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setEpisodeNumber(episode.getEpisodeNumber());
simpleItem.setSeriesNumber(episode.getSeriesNumber());
}
} else if (fullItem instanceof Film && (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION))) {
Film film = (Film) fullItem;
simpleItem.setYear(film.getYear());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setOriginalLanguages(languagesFrom(film.getLanguages()));
simpleItem.setSubtitles(simpleSubtitlesFrom(film.getSubtitles()));
simpleItem.setCertificates(simpleCertificates(film.getCertificates()));
simpleItem.setReleaseDates(simpleReleaseDate(film.getReleaseDates()));
}
} else if (fullItem instanceof Song) {
Song song = (Song) fullItem;
simpleItem.setIsrc(song.getIsrc());
+ simpleItem.setDuration(song.getDuration().getStandardSeconds());
}
}
private Iterable<org.atlasapi.media.entity.simple.ReleaseDate> simpleReleaseDate(Set<ReleaseDate> releaseDates) {
return Iterables.transform(releaseDates, new Function<ReleaseDate, org.atlasapi.media.entity.simple.ReleaseDate>() {
@Override
public org.atlasapi.media.entity.simple.ReleaseDate apply(ReleaseDate input) {
return new org.atlasapi.media.entity.simple.ReleaseDate(
input.date().toDateTimeAtStartOfDay(DateTimeZones.UTC).toDate(),
input.country().code(),
input.type().toString().toLowerCase()
);
}
});
}
private Iterable<org.atlasapi.media.entity.simple.Certificate> simpleCertificates(Set<Certificate> certificates) {
return Iterables.transform(certificates, new Function<Certificate, org.atlasapi.media.entity.simple.Certificate>() {
@Override
public org.atlasapi.media.entity.simple.Certificate apply(Certificate input) {
return new org.atlasapi.media.entity.simple.Certificate(input.classification(), input.country().code());
}
});
}
public Iterable<org.atlasapi.media.entity.simple.Subtitles> simpleSubtitlesFrom(Set<Subtitles> subtitles) {
return Iterables.filter(Iterables.transform(subtitles, new Function<Subtitles,org.atlasapi.media.entity.simple.Subtitles>(){
@Override
public org.atlasapi.media.entity.simple.Subtitles apply(Subtitles input) {
Language lang = languageForCode(input.code());
return lang == null ? null : new org.atlasapi.media.entity.simple.Subtitles(lang);
}
}
),Predicates.notNull());
}
public Iterable<Language> languagesFrom(Set<String> languages) {
return Iterables.filter(Iterables.transform(languages, new Function<String, Language>() {
@Override
public Language apply(String input) {
return languageForCode(input);
}
}), Predicates.notNull());
}
public Language languageForCode(String input) {
Locale locale = localeMap.get(input);
if (locale == null) {
return null;
}
return new Language(locale.getLanguage(), locale.getDisplayLanguage());
}
private void addTo(org.atlasapi.media.entity.simple.Item simpleItem, Version version, Item item, Set<Annotation> annotations) {
if (annotations.contains(Annotation.LOCATIONS) || annotations.contains(Annotation.AVAILABLE_LOCATIONS)) {
for (Encoding encoding : version.getManifestedAs()) {
addTo(simpleItem, version, encoding, item, annotations);
}
}
Iterable<Broadcast> broadcasts = null;
if (annotations.contains(Annotation.BROADCASTS)) {
broadcasts = filterInactive(version.getBroadcasts());
} else if (annotations.contains(Annotation.FIRST_BROADCASTS)) {
broadcasts = firstBroadcasts(filterInactive(version.getBroadcasts()));
} else if (annotations.contains(Annotation.NEXT_BROADCASTS)) {
broadcasts = nextBroadcast(filterInactive(version.getBroadcasts()));
}
if (broadcasts != null) {
for (Broadcast broadcast : broadcasts) {
org.atlasapi.media.entity.simple.Broadcast simpleBroadcast = simplify(broadcast);
copyProperties(version, simpleBroadcast, item);
simpleItem.addBroadcast(simpleBroadcast);
}
}
}
private Iterable<Broadcast> nextBroadcast(Iterable<Broadcast> broadcasts) {
DateTime now = clock.now();
DateTime earliest = null;
Builder<Broadcast> filteredBroadcasts = ImmutableSet.builder();
for (Broadcast broadcast : broadcasts) {
DateTime transmissionTime = broadcast.getTransmissionTime();
if (transmissionTime.isAfter(now) && (earliest == null || transmissionTime.isBefore(earliest))) {
earliest = transmissionTime;
filteredBroadcasts = ImmutableSet.<Broadcast>builder().add(broadcast);
} else if (transmissionTime.isEqual(earliest)) {
filteredBroadcasts.add(broadcast);
}
}
return filteredBroadcasts.build();
}
private Iterable<Broadcast> firstBroadcasts(Iterable<Broadcast> broadcasts) {
DateTime earliest = null;
Builder<Broadcast> filteredBroadcasts = ImmutableSet.builder();
for (Broadcast broadcast : broadcasts) {
DateTime transmissionTime = broadcast.getTransmissionTime();
if (earliest == null || transmissionTime.isBefore(earliest)) {
earliest = transmissionTime;
filteredBroadcasts = ImmutableSet.<Broadcast>builder().add(broadcast);
} else if (transmissionTime.isEqual(earliest)) {
filteredBroadcasts.add(broadcast);
}
}
return filteredBroadcasts.build();
}
private Iterable<Broadcast> filterInactive(Iterable<Broadcast> broadcasts) {
return Iterables.filter(broadcasts, new Predicate<Broadcast>() {
@Override
public boolean apply(Broadcast input) {
return input.isActivelyPublished();
}
});
}
private org.atlasapi.media.entity.simple.Broadcast simplify(Broadcast broadcast) {
org.atlasapi.media.entity.simple.Broadcast simpleModel = new org.atlasapi.media.entity.simple.Broadcast(broadcast.getBroadcastOn(), broadcast.getTransmissionTime(),
broadcast.getTransmissionEndTime(), broadcast.getSourceId());
simpleModel.setRepeat(broadcast.getRepeat());
simpleModel.setSubtitled(broadcast.getSubtitled());
simpleModel.setSigned(broadcast.getSigned());
simpleModel.setAudioDescribed(broadcast.getAudioDescribed());
simpleModel.setHighDefinition(broadcast.getHighDefinition());
simpleModel.setWidescreen(broadcast.getWidescreen());
simpleModel.setSurround(broadcast.getSurround());
simpleModel.setLive(broadcast.getLive());
simpleModel.setPremiere(broadcast.getPremiere());
simpleModel.setNewSeries(broadcast.getNewSeries());
return simpleModel;
}
private void copyProperties(Version version, org.atlasapi.media.entity.simple.Version simpleLocation, org.atlasapi.media.entity.Item item) {
simpleLocation.setPublishedDuration(version.getPublishedDuration());
simpleLocation.setDuration(durationFrom(item, version));
simpleLocation.set3d(version.is3d());
Restriction restriction = new Restriction();
if (version.getRestriction() != null) {
restriction.setRestricted(version.getRestriction().isRestricted());
restriction.setMinimumAge(version.getRestriction().getMinimumAge());
restriction.setMessage(version.getRestriction().getMessage());
}
simpleLocation.setRestriction(restriction);
}
// temporary fix: some versions are missing durations so
// we fall back to the broadcast and location durations
private Integer durationFrom(org.atlasapi.media.entity.Item item, Version version) {
if (version.getDuration() != null && version.getDuration() > 0) {
return version.getDuration();
}
Iterable<Broadcast> broadcasts = item.flattenBroadcasts();
if (Iterables.isEmpty(broadcasts)) {
return null;
}
return Ordering.natural().max(Iterables.transform(broadcasts, new Function<Broadcast, Integer>() {
@Override
public Integer apply(Broadcast input) {
Integer duration = input.getBroadcastDuration();
if (duration == null) {
return 0;
}
return duration;
}
}));
}
private void addTo(org.atlasapi.media.entity.simple.Item simpleItem, Version version, Encoding encoding, Item item, Set<Annotation> annotations) {
DateTime now = new DateTime(DateTimeZones.UTC);
for (Location location : encoding.getAvailableAt()) {
if(!annotations.contains(Annotation.AVAILABLE_LOCATIONS) || location.getPolicy() == null || available(location.getPolicy(), now)) {
addTo(simpleItem, version, encoding, location, item);
}
}
}
private boolean available(Policy policy, DateTime now) {
return policy.getAvailabilityStart() == null
|| policy.getAvailabilityEnd() == null
|| policy.getAvailabilityStart().isBefore(now) && policy.getAvailabilityEnd().isAfter(now);
}
private void addTo(org.atlasapi.media.entity.simple.Item simpleItem, Version version, Encoding encoding, Location location, Item item) {
org.atlasapi.media.entity.simple.Location simpleLocation = new org.atlasapi.media.entity.simple.Location();
copyProperties(version, simpleLocation, item);
copyProperties(encoding, simpleLocation);
copyProperties(location, simpleLocation);
simpleItem.addLocation(simpleLocation);
}
private SeriesSummary seriesSummaryFromResolved(ParentRef seriesRef, Set<Annotation> annotations) {
SeriesSummary baseSummary = new SeriesSummary();
baseSummary.setUri(seriesRef.getUri());
return annotations.contains(Annotation.SERIES_SUMMARY) ? containerSummaryResolver.summarizeSeries(seriesRef).or(baseSummary) : baseSummary;
}
private BrandSummary summaryFromResolved(ParentRef container, Set<Annotation> annotations) {
BrandSummary baseSummary = new BrandSummary();
baseSummary.setUri(container.getUri());
return annotations.contains(Annotation.BRAND_SUMMARY) ? containerSummaryResolver.summarizeTopLevelContainer(container).or(baseSummary) : baseSummary;
}
private void copyProperties(Encoding encoding, org.atlasapi.media.entity.simple.Location simpleLocation) {
simpleLocation.setAdvertisingDuration(encoding.getAdvertisingDuration());
simpleLocation.setAudioBitRate(encoding.getAudioBitRate());
simpleLocation.setAudioChannels(encoding.getAudioChannels());
simpleLocation.setBitRate(encoding.getBitRate());
simpleLocation.setContainsAdvertising(encoding.getContainsAdvertising());
if (encoding.getDataContainerFormat() != null) {
simpleLocation.setDataContainerFormat(encoding.getDataContainerFormat().toString());
}
simpleLocation.setDataSize(encoding.getDataSize());
simpleLocation.setDistributor(encoding.getDistributor());
simpleLocation.setHasDOG(encoding.getHasDOG());
simpleLocation.setSource(encoding.getSource());
simpleLocation.setVideoAspectRatio(encoding.getVideoAspectRatio());
simpleLocation.setVideoBitRate(encoding.getVideoBitRate());
if (encoding.getVideoCoding() != null) {
simpleLocation.setVideoCoding(encoding.getVideoCoding().toString());
}
if (encoding.getAudioCoding() != null) {
simpleLocation.setAudioCoding(encoding.getAudioCoding().toString());
}
simpleLocation.setVideoFrameRate(encoding.getVideoFrameRate());
simpleLocation.setVideoHorizontalSize(encoding.getVideoHorizontalSize());
simpleLocation.setVideoProgressiveScan(encoding.getVideoProgressiveScan());
simpleLocation.setVideoVerticalSize(encoding.getVideoVerticalSize());
}
private void copyProperties(Location location, org.atlasapi.media.entity.simple.Location simpleLocation) {
Policy policy = location.getPolicy();
if (policy != null) {
if (policy.getAvailabilityStart() != null) {
simpleLocation.setAvailabilityStart(policy.getAvailabilityStart().toDate());
}
if (policy.getAvailabilityEnd() != null) {
simpleLocation.setAvailabilityEnd(policy.getAvailabilityEnd().toDate());
}
if (policy.getDrmPlayableFrom() != null) {
simpleLocation.setDrmPlayableFrom(policy.getDrmPlayableFrom().toDate());
}
if (policy.getAvailableCountries() != null) {
simpleLocation.setAvailableCountries(Countries.toCodes(policy.getAvailableCountries()));
}
if (policy.getRevenueContract() != null) {
simpleLocation.setRevenueContract(policy.getRevenueContract().key());
}
if (policy.getPrice() != null) {
simpleLocation.setPrice(policy.getPrice().getAmount());
simpleLocation.setCurrency(policy.getPrice().getCurrency().getCurrencyCode());
}
if (policy.getPlatform() != null) {
simpleLocation.setPlatform(policy.getPlatform().key());
}
}
simpleLocation.setTransportIsLive(location.getTransportIsLive());
if (location.getTransportType() != null) {
simpleLocation.setTransportType(location.getTransportType().toString());
}
if (location.getTransportSubType() != null) {
simpleLocation.setTransportSubType(location.getTransportSubType().toString());
}
simpleLocation.setUri(location.getUri());
simpleLocation.setEmbedCode(location.getEmbedCode());
simpleLocation.setEmbedId(location.getEmbedId());
}
}
| true | true | private void copyProperties(Item fullItem, org.atlasapi.media.entity.simple.Item simpleItem, Set<Annotation> annotations, ApplicationConfiguration config) {
copyBasicContentAttributes(fullItem, simpleItem, annotations, config);
simpleItem.setType(EntityType.from(fullItem).toString());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setBlackAndWhite(fullItem.getBlackAndWhite());
simpleItem.setCountriesOfOrigin(fullItem.getCountriesOfOrigin());
simpleItem.setScheduleOnly(fullItem.isScheduleOnly());
}
if (fullItem.getContainer() != null) {
simpleItem.setBrandSummary(summaryFromResolved(fullItem.getContainer(), annotations));
}
if (fullItem instanceof Episode) {
Episode episode = (Episode) fullItem;
if (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION) || annotations.contains(Annotation.SERIES_SUMMARY)) {
ParentRef series = episode.getSeriesRef();
if (series != null) {
simpleItem.setSeriesSummary(seriesSummaryFromResolved(series, annotations));
}
}
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setEpisodeNumber(episode.getEpisodeNumber());
simpleItem.setSeriesNumber(episode.getSeriesNumber());
}
} else if (fullItem instanceof Film && (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION))) {
Film film = (Film) fullItem;
simpleItem.setYear(film.getYear());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setOriginalLanguages(languagesFrom(film.getLanguages()));
simpleItem.setSubtitles(simpleSubtitlesFrom(film.getSubtitles()));
simpleItem.setCertificates(simpleCertificates(film.getCertificates()));
simpleItem.setReleaseDates(simpleReleaseDate(film.getReleaseDates()));
}
} else if (fullItem instanceof Song) {
Song song = (Song) fullItem;
simpleItem.setIsrc(song.getIsrc());
}
}
| private void copyProperties(Item fullItem, org.atlasapi.media.entity.simple.Item simpleItem, Set<Annotation> annotations, ApplicationConfiguration config) {
copyBasicContentAttributes(fullItem, simpleItem, annotations, config);
simpleItem.setType(EntityType.from(fullItem).toString());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setBlackAndWhite(fullItem.getBlackAndWhite());
simpleItem.setCountriesOfOrigin(fullItem.getCountriesOfOrigin());
simpleItem.setScheduleOnly(fullItem.isScheduleOnly());
}
if (fullItem.getContainer() != null) {
simpleItem.setBrandSummary(summaryFromResolved(fullItem.getContainer(), annotations));
}
if (fullItem instanceof Episode) {
Episode episode = (Episode) fullItem;
if (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION) || annotations.contains(Annotation.SERIES_SUMMARY)) {
ParentRef series = episode.getSeriesRef();
if (series != null) {
simpleItem.setSeriesSummary(seriesSummaryFromResolved(series, annotations));
}
}
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setEpisodeNumber(episode.getEpisodeNumber());
simpleItem.setSeriesNumber(episode.getSeriesNumber());
}
} else if (fullItem instanceof Film && (annotations.contains(Annotation.DESCRIPTION) || annotations.contains(Annotation.EXTENDED_DESCRIPTION))) {
Film film = (Film) fullItem;
simpleItem.setYear(film.getYear());
if (annotations.contains(Annotation.EXTENDED_DESCRIPTION)) {
simpleItem.setOriginalLanguages(languagesFrom(film.getLanguages()));
simpleItem.setSubtitles(simpleSubtitlesFrom(film.getSubtitles()));
simpleItem.setCertificates(simpleCertificates(film.getCertificates()));
simpleItem.setReleaseDates(simpleReleaseDate(film.getReleaseDates()));
}
} else if (fullItem instanceof Song) {
Song song = (Song) fullItem;
simpleItem.setIsrc(song.getIsrc());
simpleItem.setDuration(song.getDuration().getStandardSeconds());
}
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java
index e0dff3929..da61c3cc9 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/ITabsheet.java
@@ -1,252 +1,252 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SourcesTabEvents;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabListener;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.Caption;
import com.itmill.toolkit.terminal.gwt.client.ContainerResizedListener;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
import com.itmill.toolkit.terminal.gwt.client.Util;
public class ITabsheet extends ITabsheetBase implements
ContainerResizedListener {
public static final String CLASSNAME = "i-tabsheet";
private final TabBar tb;
private final ITabsheetPanel tp;
private final Element contentNode, deco;
private String height;
private String width;
/**
* Previous visible widget is set invisible with CSS (not display: none, but
* visibility: hidden), to avoid flickering during render process. Normal
* visibility must be returned later when new widget is rendered.
*/
private Widget previousVisibleWidget;
private final TabListener tl = new TabListener() {
public void onTabSelected(SourcesTabEvents sender, final int tabIndex) {
if (client != null && activeTabIndex != tabIndex) {
addStyleDependentName("loading");
// run updating variables in deferred command to bypass some FF
// optimization issues
DeferredCommand.addCommand(new Command() {
public void execute() {
previousVisibleWidget = tp.getWidget(tp
.getVisibleWidget());
DOM.setStyleAttribute(previousVisibleWidget
.getElement(), "visibility", "hidden");
client.updateVariable(id, "selected", ""
+ tabKeys.get(tabIndex), true);
}
});
}
}
public boolean onBeforeTabSelected(SourcesTabEvents sender, int tabIndex) {
if (disabled) {
return false;
}
return true;
}
};
public ITabsheet() {
super(CLASSNAME);
tb = new TabBar();
tp = new ITabsheetPanel();
tp.setStyleName(CLASSNAME + "-tabsheetpanel");
contentNode = DOM.createDiv();
deco = DOM.createDiv();
addStyleDependentName("loading"); // Indicate initial progress
tb.setStyleName(CLASSNAME + "-tabs");
DOM
.setElementProperty(contentNode, "className", CLASSNAME
+ "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
add(tb);
DOM.appendChild(getElement(), contentNode);
insert(tp, contentNode, 0, true);
DOM.appendChild(getElement(), deco);
tb.addTabListener(tl);
clear();
// TODO Use for Safari only. Fix annoying 1px first cell in TabBar.
DOM.setStyleAttribute(DOM.getFirstChild(DOM.getFirstChild(DOM
.getFirstChild(tb.getElement()))), "display", "none");
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
// Add proper stylenames for all elements (easier to prevent unwanted
// style inheritance)
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
- final String contentBaseClass = "CLASSNAME" + "-content";
+ final String contentBaseClass = CLASSNAME + "-content";
String contentClass = contentBaseClass;
final String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
tb.addStyleDependentName(styles[i]);
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(contentNode, "className", contentClass);
DOM.setElementProperty(deco, "className", decoClass);
} else {
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(contentNode, "className", CLASSNAME
+ "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
}
if (uidl.hasAttribute("hidetabs")) {
tb.setVisible(false);
addStyleName(CLASSNAME + "-hidetabs");
} else {
tb.setVisible(true);
removeStyleName(CLASSNAME + "-hidetabs");
}
}
protected void renderTab(final UIDL tabUidl, int index, boolean selected) {
// TODO check indexes, now new tabs get placed last (changing tab order
// is not supported from server-side)
Caption c = new Caption(null, client);
c.updateCaption(tabUidl);
tb.addTab(c);
if (selected) {
renderContent(tabUidl.getChildUIDL(0));
tb.selectTab(index);
}
// Add place-holder content
tp.add(new Label(""));
}
protected void selectTab(int index, final UIDL contentUidl) {
if (index != activeTabIndex) {
activeTabIndex = index;
}
renderContent(contentUidl);
}
private void renderContent(final UIDL contentUIDL) {
DeferredCommand.addCommand(new Command() {
public void execute() {
final Paintable content = client.getPaintable(contentUIDL);
if (tp.getWidgetCount() > activeTabIndex) {
Widget old = tp.getWidget(activeTabIndex);
if (old != content) {
tp.remove(activeTabIndex);
if (old instanceof Paintable) {
client.unregisterPaintable((Paintable) old);
}
tp.insert((Widget) content, activeTabIndex);
}
} else {
tp.add((Widget) content);
}
tp.showWidget(activeTabIndex);
ITabsheet.this.iLayout();
(content).updateFromUIDL(contentUIDL, client);
ITabsheet.this.removeStyleDependentName("loading");
if (previousVisibleWidget != null) {
DOM.setStyleAttribute(previousVisibleWidget.getElement(),
"visibility", "");
previousVisibleWidget = null;
}
}
});
}
public void clear() {
int i = tb.getTabCount();
while (i > 0) {
tb.removeTab(--i);
}
tp.clear();
// Get rid of unnecessary 100% cell heights in TabBar (really ugly hack)
final Element tr = DOM.getChild(DOM.getChild(tb.getElement(), 0), 0);
final Element rest = DOM.getChild(DOM.getChild(tr, DOM
.getChildCount(tr) - 1), 0);
DOM.removeElementAttribute(rest, "style");
}
public void setHeight(String height) {
if (this.height == null && height == null) {
return;
}
String oldHeight = this.height;
this.height = height;
if ((this.height != null && height == null)
|| (this.height == null && height != null)
|| !height.equals(oldHeight)) {
iLayout();
}
}
public void setWidth(String width) {
String oldWidth = this.width;
this.width = width;
if ("100%".equals(width)) {
// Allow browser to calculate width
super.setWidth("");
} else {
super.setWidth(width);
}
if ((this.width != null && width == null)
|| (this.width == null && width != null)
|| !width.equals(oldWidth)) {
// Run descendant layout functions
Util.runDescendentsLayout(this);
}
}
public void iLayout() {
if (height != null && height != "") {
super.setHeight(height);
final int contentHeight = getOffsetHeight()
- DOM.getElementPropertyInt(deco, "offsetHeight")
- tb.getOffsetHeight();
// Set proper values for content element
DOM.setStyleAttribute(contentNode, "height", contentHeight + "px");
DOM.setStyleAttribute(contentNode, "overflow", "auto");
tp.setHeight("100%");
} else {
DOM.setStyleAttribute(contentNode, "height", "");
DOM.setStyleAttribute(contentNode, "overflow", "");
}
Util.runDescendentsLayout(this);
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
// Add proper stylenames for all elements (easier to prevent unwanted
// style inheritance)
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
final String contentBaseClass = "CLASSNAME" + "-content";
String contentClass = contentBaseClass;
final String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
tb.addStyleDependentName(styles[i]);
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(contentNode, "className", contentClass);
DOM.setElementProperty(deco, "className", decoClass);
} else {
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(contentNode, "className", CLASSNAME
+ "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
}
if (uidl.hasAttribute("hidetabs")) {
tb.setVisible(false);
addStyleName(CLASSNAME + "-hidetabs");
} else {
tb.setVisible(true);
removeStyleName(CLASSNAME + "-hidetabs");
}
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
super.updateFromUIDL(uidl, client);
// Add proper stylenames for all elements (easier to prevent unwanted
// style inheritance)
if (uidl.hasAttribute("style")) {
final String[] styles = uidl.getStringAttribute("style").split(" ");
final String contentBaseClass = CLASSNAME + "-content";
String contentClass = contentBaseClass;
final String decoBaseClass = CLASSNAME + "-deco";
String decoClass = decoBaseClass;
for (int i = 0; i < styles.length; i++) {
tb.addStyleDependentName(styles[i]);
contentClass += " " + contentBaseClass + "-" + styles[i];
decoClass += " " + decoBaseClass + "-" + styles[i];
}
DOM.setElementProperty(contentNode, "className", contentClass);
DOM.setElementProperty(deco, "className", decoClass);
} else {
tb.setStyleName(CLASSNAME + "-tabs");
DOM.setElementProperty(contentNode, "className", CLASSNAME
+ "-content");
DOM.setElementProperty(deco, "className", CLASSNAME + "-deco");
}
if (uidl.hasAttribute("hidetabs")) {
tb.setVisible(false);
addStyleName(CLASSNAME + "-hidetabs");
} else {
tb.setVisible(true);
removeStyleName(CLASSNAME + "-hidetabs");
}
}
|
diff --git a/source/org/jivesoftware/smackx/provider/XHTMLExtensionProvider.java b/source/org/jivesoftware/smackx/provider/XHTMLExtensionProvider.java
index 9d8e6c35..f216ef3c 100644
--- a/source/org/jivesoftware/smackx/provider/XHTMLExtensionProvider.java
+++ b/source/org/jivesoftware/smackx/provider/XHTMLExtensionProvider.java
@@ -1,110 +1,110 @@
/**
* $RCSfile$
* $Revision$
* $Date$
*
* Copyright (C) 2002-2003 Jive Software. All rights reserved.
* ====================================================================
* The Jive Software License (based on Apache Software License, Version 1.1)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by
* Jive Software (http://www.jivesoftware.com)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Smack" and "Jive Software" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please
* contact [email protected].
*
* 5. Products derived from this software may not be called "Smack",
* nor may "Smack" appear in their name, without prior written
* permission of Jive Software.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL JIVE SOFTWARE OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*/
package org.jivesoftware.smackx.provider;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.provider.PacketExtensionProvider;
import org.jivesoftware.smackx.packet.XHTMLExtension;
import org.xmlpull.v1.XmlPullParser;
/**
* The XHTMLExtensionProvider parses XHTML packets.
*
* @author Gaston Dombiak
*/
public class XHTMLExtensionProvider implements PacketExtensionProvider {
/**
* Creates a new XHTMLExtensionProvider.
* ProviderManager requires that every PacketExtensionProvider has a public, no-argument constructor
*/
public XHTMLExtensionProvider() {
}
/**
* Parses a XHTMLExtension packet (extension sub-packet).
*
* @param parser the XML parser, positioned at the starting element of the extension.
* @return a PacketExtension.
* @throws Exception if a parsing error occurs.
*/
public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
XHTMLExtension xhtmlExtension = new XHTMLExtension();
boolean done = false;
- StringBuffer buffer = null;
+ StringBuffer buffer = new StringBuffer();;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("body"))
buffer = new StringBuffer();
buffer.append(parser.getText());
} else if (eventType == XmlPullParser.TEXT) {
if (buffer != null) buffer.append(parser.getText());
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("body")) {
buffer.append(parser.getText());
xhtmlExtension.addBody(buffer.toString());
}
else if (parser.getName().equals(xhtmlExtension.getElementName())) {
done = true;
}
else
buffer.append(parser.getText());
}
}
return xhtmlExtension;
}
}
| true | true | public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
XHTMLExtension xhtmlExtension = new XHTMLExtension();
boolean done = false;
StringBuffer buffer = null;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("body"))
buffer = new StringBuffer();
buffer.append(parser.getText());
} else if (eventType == XmlPullParser.TEXT) {
if (buffer != null) buffer.append(parser.getText());
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("body")) {
buffer.append(parser.getText());
xhtmlExtension.addBody(buffer.toString());
}
else if (parser.getName().equals(xhtmlExtension.getElementName())) {
done = true;
}
else
buffer.append(parser.getText());
}
}
return xhtmlExtension;
}
| public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
XHTMLExtension xhtmlExtension = new XHTMLExtension();
boolean done = false;
StringBuffer buffer = new StringBuffer();;
while (!done) {
int eventType = parser.next();
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("body"))
buffer = new StringBuffer();
buffer.append(parser.getText());
} else if (eventType == XmlPullParser.TEXT) {
if (buffer != null) buffer.append(parser.getText());
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("body")) {
buffer.append(parser.getText());
xhtmlExtension.addBody(buffer.toString());
}
else if (parser.getName().equals(xhtmlExtension.getElementName())) {
done = true;
}
else
buffer.append(parser.getText());
}
}
return xhtmlExtension;
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VOverlay.java b/src/com/vaadin/terminal/gwt/client/ui/VOverlay.java
index fb6831e31..43f08b6a0 100644
--- a/src/com/vaadin/terminal/gwt/client/ui/VOverlay.java
+++ b/src/com/vaadin/terminal/gwt/client/ui/VOverlay.java
@@ -1,296 +1,297 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import com.google.gwt.animation.client.Animation;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Util;
/**
* In Vaadin UI this Overlay should always be used for all elements that
* temporary float over other components like context menus etc. This is to deal
* stacking order correctly with VWindow objects.
*/
public class VOverlay extends PopupPanel {
/*
* The z-index value from where all overlays live. This can be overridden in
* any extending class.
*/
protected static int Z_INDEX = 20000;
/*
* Shadow element style. If an extending class wishes to use a different
* style of shadow, it can use setShadowStyle(String) to give the shadow
* element a new style name.
*/
public static final String CLASSNAME_SHADOW = "v-shadow";
/*
* The shadow element for this overlay.
*/
private Element shadow;
/**
* The HTML snippet that is used to render the actual shadow. In consists of
* nine different DIV-elements with the following class names:
*
* <pre>
* .v-shadow[-stylename]
* ----------------------------------------------
* | .top-left | .top | .top-right |
* |---------------|-----------|----------------|
* | | | |
* | .left | .center | .right |
* | | | |
* |---------------|-----------|----------------|
* | .bottom-left | .bottom | .bottom-right |
* ----------------------------------------------
* </pre>
*
* See default theme 'shadow.css' for implementation example.
*/
private static final String SHADOW_HTML = "<div class=\"top-left\"></div><div class=\"top\"></div><div class=\"top-right\"></div><div class=\"left\"></div><div class=\"center\"></div><div class=\"right\"></div><div class=\"bottom-left\"></div><div class=\"bottom\"></div><div class=\"bottom-right\"></div>";
public VOverlay() {
super();
adjustZIndex();
}
public VOverlay(boolean autoHide) {
super(autoHide);
adjustZIndex();
}
public VOverlay(boolean autoHide, boolean modal) {
super(autoHide, modal);
adjustZIndex();
}
public VOverlay(boolean autoHide, boolean modal, boolean showShadow) {
super(autoHide, modal);
if (showShadow) {
shadow = DOM.createDiv();
shadow.setClassName(CLASSNAME_SHADOW);
shadow.setInnerHTML(SHADOW_HTML);
DOM.setStyleAttribute(shadow, "position", "absolute");
addCloseHandler(new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
if (shadow.getParentElement() != null) {
shadow.getParentElement().removeChild(shadow);
}
}
});
}
adjustZIndex();
}
private void adjustZIndex() {
setZIndex(Z_INDEX);
}
/**
* Set the z-index (visual stack position) for this overlay.
*
* @param zIndex
* The new z-index
*/
protected void setZIndex(int zIndex) {
DOM.setStyleAttribute(getElement(), "zIndex", "" + zIndex);
if (shadow != null) {
DOM.setStyleAttribute(shadow, "zIndex", "" + zIndex);
}
}
@Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (shadow != null) {
updateShadowSizeAndPosition(isAnimationEnabled() ? 0 : 1);
}
}
@Override
public void show() {
super.show();
if (shadow != null) {
if (isAnimationEnabled()) {
ShadowAnimation sa = new ShadowAnimation();
sa.run(200);
} else {
updateShadowSizeAndPosition(1.0);
}
}
Util.runIE7ZeroSizedBodyFix();
}
@Override
public void hide(boolean autoClosed) {
super.hide(autoClosed);
Util.runIE7ZeroSizedBodyFix();
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (shadow != null) {
shadow.getStyle().setProperty("visibility",
visible ? "visible" : "hidden");
}
}
@Override
public void setWidth(String width) {
super.setWidth(width);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
@Override
public void setHeight(String height) {
super.setHeight(height);
if (shadow != null) {
updateShadowSizeAndPosition(1.0);
}
}
/**
* Sets the shadow style for this overlay. Will override any previous style
* for the shadow. The default style name is defined by CLASSNAME_SHADOW.
* The given style will be prefixed with CLASSNAME_SHADOW.
*
* @param style
* The new style name for the shadow element. Will be prefixed by
* CLASSNAME_SHADOW, e.g. style=='foobar' -> actual style
* name=='v-shadow-foobar'.
*/
protected void setShadowStyle(String style) {
if (shadow != null) {
shadow.setClassName(CLASSNAME_SHADOW + "-" + style);
}
}
/*
* Extending classes should always call this method after they change the
* size of overlay without using normal 'setWidth(String)' and
* 'setHeight(String)' methods (if not calling super.setWidth/Height).
*/
protected void updateShadowSizeAndPosition() {
updateShadowSizeAndPosition(1.0);
}
/**
* Recalculates proper position and dimensions for the shadow element. Can
* be used to animate the shadow, using the 'progress' parameter (used to
* animate the shadow in sync with GWT PopupPanel's default animation
* 'PopupPanel.AnimationType.CENTER').
*
* @param progress
* A value between 0.0 and 1.0, indicating the progress of the
* animation (0=start, 1=end).
*/
private void updateShadowSizeAndPosition(final double progress) {
// Don't do anything if overlay element is not attached
if (!isAttached()) {
return;
}
// Calculate proper z-index
String zIndex = null;
try {
// Odd behaviour with Windows Hosted Mode forces us to use
// this redundant try/catch block (See dev.vaadin.com #2011)
zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
} catch (Exception ignore) {
// Ignored, will cause no harm
+ zIndex = "1000";
}
if (zIndex == null) {
zIndex = "" + Z_INDEX;
}
// Calculate position and size
if (BrowserInfo.get().isIE()) {
// Shake IE
getOffsetHeight();
getOffsetWidth();
}
int x = getAbsoluteLeft();
int y = getAbsoluteTop();
/* This is needed for IE7 at least */
// Account for the difference between absolute position and the
// body's positioning context.
x -= Document.get().getBodyOffsetLeft();
y -= Document.get().getBodyOffsetTop();
int width = getOffsetWidth();
int height = getOffsetHeight();
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
// Animate the shadow size
x += (int) (width * (1.0 - progress) / 2.0);
y += (int) (height * (1.0 - progress) / 2.0);
width = (int) (width * progress);
height = (int) (height * progress);
// Opera needs some shaking to get parts of the shadow showing
// properly
// (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// Clear the height of all middle elements
DOM.getChild(shadow, 3).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 4).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 5).getStyle().setProperty("height", "auto");
}
// Update correct values
DOM.setStyleAttribute(shadow, "zIndex", zIndex);
DOM.setStyleAttribute(shadow, "width", width + "px");
DOM.setStyleAttribute(shadow, "height", height + "px");
DOM.setStyleAttribute(shadow, "top", y + "px");
DOM.setStyleAttribute(shadow, "left", x + "px");
DOM.setStyleAttribute(shadow, "display", progress < 0.9 ? "none" : "");
// Opera fix, part 2 (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// We'll fix the height of all the middle elements
DOM.getChild(shadow, 3).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 3).getOffsetHeight());
DOM.getChild(shadow, 4).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 4).getOffsetHeight());
DOM.getChild(shadow, 5).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 5).getOffsetHeight());
}
// Attach to dom if not there already
if (shadow.getParentElement() == null) {
RootPanel.get().getElement().insertBefore(shadow, getElement());
}
}
protected class ShadowAnimation extends Animation {
@Override
protected void onUpdate(double progress) {
if (shadow != null) {
updateShadowSizeAndPosition(progress);
}
}
}
}
| true | true | private void updateShadowSizeAndPosition(final double progress) {
// Don't do anything if overlay element is not attached
if (!isAttached()) {
return;
}
// Calculate proper z-index
String zIndex = null;
try {
// Odd behaviour with Windows Hosted Mode forces us to use
// this redundant try/catch block (See dev.vaadin.com #2011)
zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
} catch (Exception ignore) {
// Ignored, will cause no harm
}
if (zIndex == null) {
zIndex = "" + Z_INDEX;
}
// Calculate position and size
if (BrowserInfo.get().isIE()) {
// Shake IE
getOffsetHeight();
getOffsetWidth();
}
int x = getAbsoluteLeft();
int y = getAbsoluteTop();
/* This is needed for IE7 at least */
// Account for the difference between absolute position and the
// body's positioning context.
x -= Document.get().getBodyOffsetLeft();
y -= Document.get().getBodyOffsetTop();
int width = getOffsetWidth();
int height = getOffsetHeight();
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
// Animate the shadow size
x += (int) (width * (1.0 - progress) / 2.0);
y += (int) (height * (1.0 - progress) / 2.0);
width = (int) (width * progress);
height = (int) (height * progress);
// Opera needs some shaking to get parts of the shadow showing
// properly
// (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// Clear the height of all middle elements
DOM.getChild(shadow, 3).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 4).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 5).getStyle().setProperty("height", "auto");
}
// Update correct values
DOM.setStyleAttribute(shadow, "zIndex", zIndex);
DOM.setStyleAttribute(shadow, "width", width + "px");
DOM.setStyleAttribute(shadow, "height", height + "px");
DOM.setStyleAttribute(shadow, "top", y + "px");
DOM.setStyleAttribute(shadow, "left", x + "px");
DOM.setStyleAttribute(shadow, "display", progress < 0.9 ? "none" : "");
// Opera fix, part 2 (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// We'll fix the height of all the middle elements
DOM.getChild(shadow, 3).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 3).getOffsetHeight());
DOM.getChild(shadow, 4).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 4).getOffsetHeight());
DOM.getChild(shadow, 5).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 5).getOffsetHeight());
}
// Attach to dom if not there already
if (shadow.getParentElement() == null) {
RootPanel.get().getElement().insertBefore(shadow, getElement());
}
}
| private void updateShadowSizeAndPosition(final double progress) {
// Don't do anything if overlay element is not attached
if (!isAttached()) {
return;
}
// Calculate proper z-index
String zIndex = null;
try {
// Odd behaviour with Windows Hosted Mode forces us to use
// this redundant try/catch block (See dev.vaadin.com #2011)
zIndex = DOM.getStyleAttribute(getElement(), "zIndex");
} catch (Exception ignore) {
// Ignored, will cause no harm
zIndex = "1000";
}
if (zIndex == null) {
zIndex = "" + Z_INDEX;
}
// Calculate position and size
if (BrowserInfo.get().isIE()) {
// Shake IE
getOffsetHeight();
getOffsetWidth();
}
int x = getAbsoluteLeft();
int y = getAbsoluteTop();
/* This is needed for IE7 at least */
// Account for the difference between absolute position and the
// body's positioning context.
x -= Document.get().getBodyOffsetLeft();
y -= Document.get().getBodyOffsetTop();
int width = getOffsetWidth();
int height = getOffsetHeight();
if (width < 0) {
width = 0;
}
if (height < 0) {
height = 0;
}
// Animate the shadow size
x += (int) (width * (1.0 - progress) / 2.0);
y += (int) (height * (1.0 - progress) / 2.0);
width = (int) (width * progress);
height = (int) (height * progress);
// Opera needs some shaking to get parts of the shadow showing
// properly
// (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// Clear the height of all middle elements
DOM.getChild(shadow, 3).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 4).getStyle().setProperty("height", "auto");
DOM.getChild(shadow, 5).getStyle().setProperty("height", "auto");
}
// Update correct values
DOM.setStyleAttribute(shadow, "zIndex", zIndex);
DOM.setStyleAttribute(shadow, "width", width + "px");
DOM.setStyleAttribute(shadow, "height", height + "px");
DOM.setStyleAttribute(shadow, "top", y + "px");
DOM.setStyleAttribute(shadow, "left", x + "px");
DOM.setStyleAttribute(shadow, "display", progress < 0.9 ? "none" : "");
// Opera fix, part 2 (ticket #2704)
if (BrowserInfo.get().isOpera()) {
// We'll fix the height of all the middle elements
DOM.getChild(shadow, 3).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 3).getOffsetHeight());
DOM.getChild(shadow, 4).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 4).getOffsetHeight());
DOM.getChild(shadow, 5).getStyle().setPropertyPx("height",
DOM.getChild(shadow, 5).getOffsetHeight());
}
// Attach to dom if not there already
if (shadow.getParentElement() == null) {
RootPanel.get().getElement().insertBefore(shadow, getElement());
}
}
|
diff --git a/android/src/gov/nasa/arc/geocam/talk/activity/AuthenticatedBaseActivity.java b/android/src/gov/nasa/arc/geocam/talk/activity/AuthenticatedBaseActivity.java
index 4404d74..bd066a2 100644
--- a/android/src/gov/nasa/arc/geocam/talk/activity/AuthenticatedBaseActivity.java
+++ b/android/src/gov/nasa/arc/geocam/talk/activity/AuthenticatedBaseActivity.java
@@ -1,96 +1,96 @@
package gov.nasa.arc.geocam.talk.activity;
import gov.nasa.arc.geocam.talk.GeoCamTalkRoboApplication;
import gov.nasa.arc.geocam.talk.R;
import gov.nasa.arc.geocam.talk.UIUtils;
import gov.nasa.arc.geocam.talk.bean.TalkServerIntent;
import gov.nasa.arc.geocam.talk.service.ISiteAuth;
import roboguice.activity.RoboActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.inject.Inject;
public class AuthenticatedBaseActivity extends RoboActivity {
@Inject
ISiteAuth siteAuth;
protected BroadcastReceiver login_failed_receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().contentEquals(TalkServerIntent.INTENT_LOGIN_FAILED.toString())) {
Toast.makeText(context, "Could not log in. Please provide login credentials.",
Toast.LENGTH_LONG);
Log.i("Talk", "AuthBase received LOGIN_FAILED intent");
UIUtils.goToLogin(context);
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.default_menu, menu);
return true;
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(TalkServerIntent.INTENT_LOGIN_FAILED.toString());
registerReceiver(login_failed_receiver, filter);
}
protected void onPause() {
unregisterReceiver(login_failed_receiver);
super.onPause();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout_menu_button:
try {
Log.i("Talk", "Logout Menu Item");
UIUtils.logout(siteAuth);
this.startActivity(new Intent(this, GeoCamTalkLogon.class));
} catch (Exception e) {
UIUtils.displayException(getApplicationContext(), e, "You're screwed");
}
return false;
case R.id.create_message_button:
Log.i("Talk", "Create Message Menu Item");
UIUtils.createTalkMessage(this);
return false;
case R.id.message_list_button:
UIUtils.goHome(this);
return false;
case R.id.exit_menu_button:
((GeoCamTalkRoboApplication) getApplication()).stopThreads();
finish();
- moveTaskToBack(true);
+ moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
return false;
case R.id.settings_button:
UIUtils.goToSettings(this);
Log.i("Talk", "Settings Menu Item");
return false;
default:
Log.i("Talk", "NO BUTTON!!!");
return super.onOptionsItemSelected(item);
}
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout_menu_button:
try {
Log.i("Talk", "Logout Menu Item");
UIUtils.logout(siteAuth);
this.startActivity(new Intent(this, GeoCamTalkLogon.class));
} catch (Exception e) {
UIUtils.displayException(getApplicationContext(), e, "You're screwed");
}
return false;
case R.id.create_message_button:
Log.i("Talk", "Create Message Menu Item");
UIUtils.createTalkMessage(this);
return false;
case R.id.message_list_button:
UIUtils.goHome(this);
return false;
case R.id.exit_menu_button:
((GeoCamTalkRoboApplication) getApplication()).stopThreads();
finish();
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
return false;
case R.id.settings_button:
UIUtils.goToSettings(this);
Log.i("Talk", "Settings Menu Item");
return false;
default:
Log.i("Talk", "NO BUTTON!!!");
return super.onOptionsItemSelected(item);
}
}
| public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout_menu_button:
try {
Log.i("Talk", "Logout Menu Item");
UIUtils.logout(siteAuth);
this.startActivity(new Intent(this, GeoCamTalkLogon.class));
} catch (Exception e) {
UIUtils.displayException(getApplicationContext(), e, "You're screwed");
}
return false;
case R.id.create_message_button:
Log.i("Talk", "Create Message Menu Item");
UIUtils.createTalkMessage(this);
return false;
case R.id.message_list_button:
UIUtils.goHome(this);
return false;
case R.id.exit_menu_button:
((GeoCamTalkRoboApplication) getApplication()).stopThreads();
finish();
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
return false;
case R.id.settings_button:
UIUtils.goToSettings(this);
Log.i("Talk", "Settings Menu Item");
return false;
default:
Log.i("Talk", "NO BUTTON!!!");
return super.onOptionsItemSelected(item);
}
}
|
diff --git a/plugins/org.eclipse.xtext.xtend2/src/org/eclipse/xtext/xtend2/formatting/MemberFromSuperImplementor.java b/plugins/org.eclipse.xtext.xtend2/src/org/eclipse/xtext/xtend2/formatting/MemberFromSuperImplementor.java
index ac9864601..1c0dad9ff 100644
--- a/plugins/org.eclipse.xtext.xtend2/src/org/eclipse/xtext/xtend2/formatting/MemberFromSuperImplementor.java
+++ b/plugins/org.eclipse.xtext.xtend2/src/org/eclipse/xtext/xtend2/formatting/MemberFromSuperImplementor.java
@@ -1,167 +1,168 @@
/*******************************************************************************
* Copyright (c) 2011 itemis AG (http://www.itemis.eu) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.xtext.xtend2.formatting;
import static com.google.common.collect.Iterables.*;
import static org.eclipse.xtext.util.Strings.*;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.Keyword;
import org.eclipse.xtext.common.types.JvmConstructor;
import org.eclipse.xtext.common.types.JvmExecutable;
import org.eclipse.xtext.common.types.JvmFormalParameter;
import org.eclipse.xtext.common.types.JvmGenericType;
import org.eclipse.xtext.common.types.JvmOperation;
import org.eclipse.xtext.common.types.JvmTypeParameter;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.eclipse.xtext.common.types.JvmVisibility;
import org.eclipse.xtext.common.types.util.ITypeArgumentContext;
import org.eclipse.xtext.common.types.util.TypeArgumentContextProvider;
import org.eclipse.xtext.common.types.util.TypeReferences;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.ILeafNode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.xbase.compiler.IAppendable;
import org.eclipse.xtext.xbase.compiler.StringBuilderBasedAppendable;
import org.eclipse.xtext.xbase.compiler.TypeReferenceSerializer;
import org.eclipse.xtext.xtend2.jvmmodel.IXtend2JvmAssociations;
import org.eclipse.xtext.xtend2.xtend2.XtendClass;
import com.google.inject.Inject;
/**
* @author Jan Koehnlein - Initial contribution and API
*/
public class MemberFromSuperImplementor {
public static final String DEFAULT_BODY = "throw new UnsupportedOperationException(\"Auto-generated function stub\")";
@Inject
private TypeArgumentContextProvider typeArgumentContextProvider;
@Inject
private TypeReferenceSerializer typeReferenceSerializer;
@Inject
private TypeReferences typeReferences;
@Inject
private IXtend2JvmAssociations associations;
public void appendOverrideFunction(final XtendClass overrider, JvmOperation overriddenOperation,
IAppendable appendable) {
appendExecutable(overrider, overriddenOperation, appendable);
}
public void appendConstructorFromSuper(final XtendClass overrider, JvmConstructor superConstructor,
IAppendable appendable) {
appendExecutable(overrider, superConstructor, appendable);
}
protected void appendExecutable(final XtendClass overrider, JvmExecutable executableFromSuper,
IAppendable appendable) {
appendable.openScope();
boolean isOperation = executableFromSuper instanceof JvmOperation;
final JvmGenericType overridingType = associations.getInferredType(overrider);
final ITypeArgumentContext typeArgumentContext = typeArgumentContextProvider
.getTypeArgumentContext(new TypeArgumentContextProvider.AbstractRequest() {
@Override
public JvmTypeReference getReceiverType() {
return typeReferences.createTypeRef(overridingType);
}
});
appendable.increaseIndentation();
appendable.append("\n");
if (isOperation)
appendable.append("override ");
if (executableFromSuper.getVisibility() == JvmVisibility.PROTECTED) {
appendable.append("protected ");
}
appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, false);
boolean isFirst;
if (!executableFromSuper.getExceptions().isEmpty()) {
appendable.append(" throws ");
isFirst = true;
for (JvmTypeReference exception : executableFromSuper.getExceptions()) {
if (!isFirst)
appendable.append(", ");
isFirst = false;
typeReferenceSerializer.serialize(exception, overridingType, appendable);
}
}
appendable.append(" {").increaseIndentation().append("\n");
if (isOperation && ((JvmOperation) executableFromSuper).isAbstract()) {
appendable.append(DEFAULT_BODY);
- } else if (isOperation) {
- appendable.append("super.");
+ } else {
+ if (isOperation)
+ appendable.append("super.");
+ appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, true);
}
- appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, true);
appendable.decreaseIndentation().append("\n}").decreaseIndentation().append("\n");
appendable.closeScope();
}
protected void appendSignature(JvmExecutable overridden, EObject context,
final ITypeArgumentContext typeArgumentContext, IAppendable appendable, boolean isCall) {
boolean isFirst = true;
if (!isEmpty(overridden.getTypeParameters())) {
appendable.append("<");
for (JvmTypeParameter typeParameter : overridden.getTypeParameters()) {
if (!isFirst)
appendable.append(", ");
isFirst = false;
appendable.append(typeParameter);
}
appendable.append("> ");
}
if (overridden instanceof JvmConstructor) {
if (isCall)
appendable.append("super");
else
appendable.append("new");
} else {
appendable.append(overridden.getSimpleName());
}
appendable.append("(");
isFirst = true;
for (JvmFormalParameter param : overridden.getParameters()) {
if (!isFirst)
appendable.append(", ");
isFirst = false;
if (isCall) {
appendable.append(appendable.getName(param));
} else {
JvmTypeReference overriddenParameterType = typeArgumentContext.getLowerBound(param.getParameterType());
typeReferenceSerializer.serialize(overriddenParameterType, context, appendable, false, false, false,
true);
String declareVariable = (appendable instanceof StringBuilderBasedAppendable) ? ((StringBuilderBasedAppendable) appendable)
.declareFreshVariable(param, param.getName()) : appendable.declareVariable(param,
param.getName());
appendable.append(" ").append(declareVariable);
}
}
appendable.append(")");
}
public int getFunctionInsertOffset(XtendClass clazz) {
ICompositeNode clazzNode = NodeModelUtils.findActualNodeFor(clazz);
int lastClosingBraceOffset = -1;
for (ILeafNode leafNode : clazzNode.getLeafNodes()) {
if (leafNode.getGrammarElement() instanceof Keyword
&& equal("}", ((Keyword) leafNode.getGrammarElement()).getValue())) {
lastClosingBraceOffset = leafNode.getOffset();
}
}
return (lastClosingBraceOffset == -1) ? lastClosingBraceOffset = clazzNode.getTotalEndOffset()
: lastClosingBraceOffset;
}
public int getConstructorInsertOffset(XtendClass clazz) {
return getFunctionInsertOffset(clazz);
}
}
| false | true | protected void appendExecutable(final XtendClass overrider, JvmExecutable executableFromSuper,
IAppendable appendable) {
appendable.openScope();
boolean isOperation = executableFromSuper instanceof JvmOperation;
final JvmGenericType overridingType = associations.getInferredType(overrider);
final ITypeArgumentContext typeArgumentContext = typeArgumentContextProvider
.getTypeArgumentContext(new TypeArgumentContextProvider.AbstractRequest() {
@Override
public JvmTypeReference getReceiverType() {
return typeReferences.createTypeRef(overridingType);
}
});
appendable.increaseIndentation();
appendable.append("\n");
if (isOperation)
appendable.append("override ");
if (executableFromSuper.getVisibility() == JvmVisibility.PROTECTED) {
appendable.append("protected ");
}
appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, false);
boolean isFirst;
if (!executableFromSuper.getExceptions().isEmpty()) {
appendable.append(" throws ");
isFirst = true;
for (JvmTypeReference exception : executableFromSuper.getExceptions()) {
if (!isFirst)
appendable.append(", ");
isFirst = false;
typeReferenceSerializer.serialize(exception, overridingType, appendable);
}
}
appendable.append(" {").increaseIndentation().append("\n");
if (isOperation && ((JvmOperation) executableFromSuper).isAbstract()) {
appendable.append(DEFAULT_BODY);
} else if (isOperation) {
appendable.append("super.");
}
appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, true);
appendable.decreaseIndentation().append("\n}").decreaseIndentation().append("\n");
appendable.closeScope();
}
| protected void appendExecutable(final XtendClass overrider, JvmExecutable executableFromSuper,
IAppendable appendable) {
appendable.openScope();
boolean isOperation = executableFromSuper instanceof JvmOperation;
final JvmGenericType overridingType = associations.getInferredType(overrider);
final ITypeArgumentContext typeArgumentContext = typeArgumentContextProvider
.getTypeArgumentContext(new TypeArgumentContextProvider.AbstractRequest() {
@Override
public JvmTypeReference getReceiverType() {
return typeReferences.createTypeRef(overridingType);
}
});
appendable.increaseIndentation();
appendable.append("\n");
if (isOperation)
appendable.append("override ");
if (executableFromSuper.getVisibility() == JvmVisibility.PROTECTED) {
appendable.append("protected ");
}
appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, false);
boolean isFirst;
if (!executableFromSuper.getExceptions().isEmpty()) {
appendable.append(" throws ");
isFirst = true;
for (JvmTypeReference exception : executableFromSuper.getExceptions()) {
if (!isFirst)
appendable.append(", ");
isFirst = false;
typeReferenceSerializer.serialize(exception, overridingType, appendable);
}
}
appendable.append(" {").increaseIndentation().append("\n");
if (isOperation && ((JvmOperation) executableFromSuper).isAbstract()) {
appendable.append(DEFAULT_BODY);
} else {
if (isOperation)
appendable.append("super.");
appendSignature(executableFromSuper, overridingType, typeArgumentContext, appendable, true);
}
appendable.decreaseIndentation().append("\n}").decreaseIndentation().append("\n");
appendable.closeScope();
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/io/diff/SVNDiffWindowBuilder.java b/javasvn/src/org/tmatesoft/svn/core/io/diff/SVNDiffWindowBuilder.java
index b95c78945..30776f627 100644
--- a/javasvn/src/org/tmatesoft/svn/core/io/diff/SVNDiffWindowBuilder.java
+++ b/javasvn/src/org/tmatesoft/svn/core/io/diff/SVNDiffWindowBuilder.java
@@ -1,399 +1,399 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://tmate.org/svn/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.io.diff;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.util.SVNDebugLog;
/**
* @version 1.0
* @author TMate Software Ltd.
*/
public class SVNDiffWindowBuilder {
private static final int MAX_DATA_CHUNK_LENGTH = 100*1024;
public static SVNDiffWindowBuilder newInstance() {
return new SVNDiffWindowBuilder();
}
private static final int HEADER = 0;
private static final int OFFSET = 1;
private static final int INSTRUCTIONS = 2;
private static final int DONE = 3;
private static final byte[] HEADER_BYTES = {'S', 'V', 'N', 0};
private int myState;
private int[] myOffsets;
private byte[] myInstructions;
private byte[] myHeader;
private SVNDiffWindow myDiffWindow;
private int myFedDataCount;
private OutputStream myNewDataStream;
private SVNDiffWindowBuilder() {
reset();
}
public void reset() {
reset(HEADER);
}
public void reset(int state) {
myOffsets = new int[5];
myHeader = new byte[4];
myInstructions = null;
myState = state;
for(int i = 0; i < myOffsets.length; i++) {
myOffsets[i] = -1;
}
for(int i = 0; i < myHeader.length; i++) {
myHeader[i] = -1;
}
myDiffWindow = null;
myNewDataStream = null;
myFedDataCount = 0;
}
public boolean isBuilt() {
return myState == DONE;
}
public SVNDiffWindow getDiffWindow() {
return myDiffWindow;
}
public int accept(byte[] bytes, int offset) {
switch (myState) {
case HEADER:
for(int i = 0; i < myHeader.length && offset < bytes.length; i++) {
if (myHeader[i] < 0) {
myHeader[i] = bytes[offset++];
}
}
if (myHeader[myHeader.length - 1] >= 0) {
myState = OFFSET;
if (offset < bytes.length) {
return accept(bytes, offset);
}
}
break;
case OFFSET:
for(int i = 0; i < myOffsets.length && offset < bytes.length; i++) {
if (myOffsets[i] < 0) {
// returns 0 if nothing was read, due to missing bytes.
offset = readInt(bytes, offset, myOffsets, i);
if (myOffsets[i] < 0) {
return offset;
}
}
}
if (myOffsets[myOffsets.length - 1] >= 0) {
myState = INSTRUCTIONS;
if (offset < bytes.length) {
return accept(bytes, offset);
}
}
break;
case INSTRUCTIONS:
if (myOffsets[3] > 0) {
if (myInstructions == null) {
myInstructions = new byte[myOffsets[3]];
}
// min of number of available and required.
int length = Math.min(bytes.length - offset, myOffsets[3]);
System.arraycopy(bytes, offset, myInstructions, myInstructions.length - myOffsets[3], length);
myOffsets[3] -= length;
if (myOffsets[3] == 0) {
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
}
}
return offset + length;
}
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
}
myState = DONE;
default:
// all is read.
}
return offset;
}
public boolean accept(InputStream is, ISVNEditor consumer, String path) throws SVNException {
switch (myState) {
case HEADER:
try {
for(int i = 0; i < myHeader.length; i++) {
if (myHeader[i] < 0) {
int r = is.read();
if (r < 0) {
break;
}
myHeader[i] = (byte) (r & 0xFF);
}
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myHeader[myHeader.length - 1] >= 0) {
myState = OFFSET;
}
break;
case OFFSET:
for(int i = 0; i < myOffsets.length; i++) {
if (myOffsets[i] < 0) {
// returns 0 if nothing was read, due to missing bytes.
// but it may be partially read!
try {
readInt(is, myOffsets, i);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myOffsets[i] < 0) {
// can't read?
return false;
}
}
}
if (myOffsets[myOffsets.length - 1] >= 0) {
myState = INSTRUCTIONS;
}
break;
case INSTRUCTIONS:
if (myOffsets[3] > 0) {
if (myInstructions == null) {
myInstructions = new byte[myOffsets[3]];
}
// min of number of available and required.
int length = myOffsets[3];
// read length bytes (!!!!)
try {
length = is.read(myInstructions, myInstructions.length - length, length);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
- if (length < 0) {
+ if (length <= 0) {
return false;
}
myOffsets[3] -= length;
if (myOffsets[3] == 0) {
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
}
break;
}
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
break;
case DONE:
try {
while(myFedDataCount < myDiffWindow.getNewDataLength()) {
int r = is.read();
if (r < 0) {
return false;
}
myNewDataStream.write(r);
myFedDataCount++;
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
SVNFileUtil.closeFile(myNewDataStream);
reset(1);
break;
default:
SVNDebugLog.logInfo("invalid diff window builder state: " + myState);
return false;
}
return true;
}
public static void save(SVNDiffWindow window, OutputStream os) throws IOException {
os.write(HEADER_BYTES);
if (window.getInstructionsCount() == 0) {
return;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for(int i = 0; i < window.getInstructionsCount(); i++) {
SVNDiffInstruction instruction = window.getInstructionAt(i);
byte first = (byte) (instruction.type << 6);
if (instruction.length <= 0x3f && instruction.length > 0) {
// single-byte lenght;
first |= (instruction.length & 0x3f);
bos.write(first & 0xff);
} else {
bos.write(first & 0xff);
writeInt(bos, instruction.length);
}
if (instruction.type == 0 || instruction.type == 1) {
writeInt(bos, instruction.offset);
}
}
long[] offsets = new long[5];
offsets[0] = window.getSourceViewOffset();
offsets[1] = window.getSourceViewLength();
offsets[2] = window.getTargetViewLength();
offsets[3] = bos.size();
offsets[4] = window.getNewDataLength();
for(int i = 0; i < offsets.length; i++) {
writeInt(os, offsets[i]);
}
os.write(bos.toByteArray());
}
public static SVNDiffWindow createReplacementDiffWindow(long dataLength) {
if (dataLength == 0) {
return new SVNDiffWindow(0, 0, dataLength, new SVNDiffInstruction[0], dataLength);
}
// divide data length in 100K segments
long totalLength = dataLength;
long offset = 0;
int instructionsCount = (int) ((dataLength / (MAX_DATA_CHUNK_LENGTH)) + 1);
Collection instructionsList = new ArrayList(instructionsCount);
while(dataLength > MAX_DATA_CHUNK_LENGTH) {
dataLength -= MAX_DATA_CHUNK_LENGTH;
instructionsList.add(new SVNDiffInstruction(SVNDiffInstruction.COPY_FROM_NEW_DATA, MAX_DATA_CHUNK_LENGTH, offset));
offset += MAX_DATA_CHUNK_LENGTH;
}
if (dataLength > 0) {
instructionsList.add(new SVNDiffInstruction(SVNDiffInstruction.COPY_FROM_NEW_DATA, dataLength, offset));
}
// SVNDiffInstruction[] instructions = {new SVNDiffInstruction(SVNDiffInstruction.COPY_FROM_NEW_DATA, dataLength, 0)};
SVNDiffInstruction[] instructions = (SVNDiffInstruction[]) instructionsList.toArray(new SVNDiffInstruction[instructionsList.size()]);
return new SVNDiffWindow(0, 0, totalLength, instructions, totalLength);
}
private static void writeInt(OutputStream os, long i) throws IOException {
if (i == 0) {
os.write(0);
return;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while(i > 0) {
byte b = (byte) (i & 0x7f);
i = i >> 7;
if (bos.size() > 0) {
b |= 0x80;
}
bos.write(b);
}
byte[] bytes = bos.toByteArray();
for(int j = bytes.length - 1; j >= 0; j--) {
os.write(bytes[j]);
}
}
private static int readInt(byte[] bytes, int offset, int[] target, int index) {
int newOffset = offset;
target[index] = 0;
while(true) {
byte b = bytes[newOffset];
target[index] = target[index] << 7;
target[index] = target[index] | (b & 0x7f);
if ((b & 0x80) != 0) {
// high bit
newOffset++;
if (newOffset >= bytes.length) {
target[index] = -1;
return offset;
}
continue;
}
// integer read.
return newOffset + 1;
}
}
private static void readInt(InputStream is, int[] target, int index) throws IOException {
target[index] = 0;
is.mark(10);
while(true) {
int r = is.read();
if (r < 0) {
is.reset();
target[index] = -1;
return;
}
byte b = (byte) (r & 0xFF);
target[index] = target[index] << 7;
target[index] = target[index] | (b & 0x7f);
if ((b & 0x80) != 0) {
continue;
}
return;
}
}
private static SVNDiffWindow createDiffWindow(int[] offsets, byte[] instructions) {
SVNDiffWindow window = new SVNDiffWindow(offsets[0], offsets[1], offsets[2],
createInstructions(instructions),
offsets[4]);
return window;
}
private static SVNDiffInstruction[] createInstructions(byte[] bytes) {
Collection instructions = new ArrayList();
int[] instr = new int[2];
for(int i = 0; i < bytes.length;) {
SVNDiffInstruction instruction = new SVNDiffInstruction();
instruction.type = (bytes[i] & 0xC0) >> 6;
instruction.length = bytes[i] & 0x3f;
i++;
if (instruction.length == 0) {
// read length from next byte
i = readInt(bytes, i, instr, 0);
instruction.length = instr[0];
}
if (instruction.type == 0 || instruction.type == 1) {
// read offset from next byte (no offset without length).
i = readInt(bytes, i, instr, 1);
instruction.offset = instr[1];
}
instructions.add(instruction);
instr[0] = 0;
instr[1] = 0;
}
return (SVNDiffInstruction[]) instructions.toArray(new SVNDiffInstruction[instructions.size()]);
}
}
| true | true | public boolean accept(InputStream is, ISVNEditor consumer, String path) throws SVNException {
switch (myState) {
case HEADER:
try {
for(int i = 0; i < myHeader.length; i++) {
if (myHeader[i] < 0) {
int r = is.read();
if (r < 0) {
break;
}
myHeader[i] = (byte) (r & 0xFF);
}
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myHeader[myHeader.length - 1] >= 0) {
myState = OFFSET;
}
break;
case OFFSET:
for(int i = 0; i < myOffsets.length; i++) {
if (myOffsets[i] < 0) {
// returns 0 if nothing was read, due to missing bytes.
// but it may be partially read!
try {
readInt(is, myOffsets, i);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myOffsets[i] < 0) {
// can't read?
return false;
}
}
}
if (myOffsets[myOffsets.length - 1] >= 0) {
myState = INSTRUCTIONS;
}
break;
case INSTRUCTIONS:
if (myOffsets[3] > 0) {
if (myInstructions == null) {
myInstructions = new byte[myOffsets[3]];
}
// min of number of available and required.
int length = myOffsets[3];
// read length bytes (!!!!)
try {
length = is.read(myInstructions, myInstructions.length - length, length);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (length < 0) {
return false;
}
myOffsets[3] -= length;
if (myOffsets[3] == 0) {
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
}
break;
}
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
break;
case DONE:
try {
while(myFedDataCount < myDiffWindow.getNewDataLength()) {
int r = is.read();
if (r < 0) {
return false;
}
myNewDataStream.write(r);
myFedDataCount++;
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
SVNFileUtil.closeFile(myNewDataStream);
reset(1);
break;
default:
SVNDebugLog.logInfo("invalid diff window builder state: " + myState);
return false;
}
return true;
}
| public boolean accept(InputStream is, ISVNEditor consumer, String path) throws SVNException {
switch (myState) {
case HEADER:
try {
for(int i = 0; i < myHeader.length; i++) {
if (myHeader[i] < 0) {
int r = is.read();
if (r < 0) {
break;
}
myHeader[i] = (byte) (r & 0xFF);
}
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myHeader[myHeader.length - 1] >= 0) {
myState = OFFSET;
}
break;
case OFFSET:
for(int i = 0; i < myOffsets.length; i++) {
if (myOffsets[i] < 0) {
// returns 0 if nothing was read, due to missing bytes.
// but it may be partially read!
try {
readInt(is, myOffsets, i);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (myOffsets[i] < 0) {
// can't read?
return false;
}
}
}
if (myOffsets[myOffsets.length - 1] >= 0) {
myState = INSTRUCTIONS;
}
break;
case INSTRUCTIONS:
if (myOffsets[3] > 0) {
if (myInstructions == null) {
myInstructions = new byte[myOffsets[3]];
}
// min of number of available and required.
int length = myOffsets[3];
// read length bytes (!!!!)
try {
length = is.read(myInstructions, myInstructions.length - length, length);
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
if (length <= 0) {
return false;
}
myOffsets[3] -= length;
if (myOffsets[3] == 0) {
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
}
break;
}
myState = DONE;
if (myDiffWindow == null) {
myDiffWindow = createDiffWindow(myOffsets, myInstructions);
myFedDataCount = 0;
myNewDataStream = consumer.textDeltaChunk(path, myDiffWindow);
if (myNewDataStream == null) {
myNewDataStream = SVNFileUtil.DUMMY_OUT;
}
}
break;
case DONE:
try {
while(myFedDataCount < myDiffWindow.getNewDataLength()) {
int r = is.read();
if (r < 0) {
return false;
}
myNewDataStream.write(r);
myFedDataCount++;
}
} catch (IOException e) {
SVNErrorManager.error(e.getMessage());
}
SVNFileUtil.closeFile(myNewDataStream);
reset(1);
break;
default:
SVNDebugLog.logInfo("invalid diff window builder state: " + myState);
return false;
}
return true;
}
|
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
index 25d86098f..acd9ee447 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryChart.java
@@ -1,672 +1,672 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.fuelgauge;
import com.android.settings.R;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.BatteryStats;
import android.os.SystemClock;
import android.os.BatteryStats.HistoryItem;
import android.telephony.ServiceState;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
public class BatteryHistoryChart extends View {
static final int SANS = 1;
static final int SERIF = 2;
static final int MONOSPACE = 3;
static final int BATTERY_WARN = 29;
static final int BATTERY_CRITICAL = 14;
// First value if for phone off; sirst value is "scanning"; following values
// are battery stats signal strength buckets.
static final int NUM_PHONE_SIGNALS = 7;
final Paint mBatteryBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint mBatteryGoodPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint mBatteryWarnPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint mBatteryCriticalPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
final Paint mChargingPaint = new Paint();
final Paint mScreenOnPaint = new Paint();
final Paint mGpsOnPaint = new Paint();
final Paint mWifiRunningPaint = new Paint();
final Paint mWakeLockPaint = new Paint();
final Paint[] mPhoneSignalPaints = new Paint[NUM_PHONE_SIGNALS];
final int[] mPhoneSignalColors = new int[] {
0x00000000, 0xffa00000, 0xffa0a000, 0xff808020,
0xff808040, 0xff808060, 0xff008000
};
final TextPaint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
final Path mBatLevelPath = new Path();
final Path mBatGoodPath = new Path();
final Path mBatWarnPath = new Path();
final Path mBatCriticalPath = new Path();
final Path mChargingPath = new Path();
final Path mScreenOnPath = new Path();
final Path mGpsOnPath = new Path();
final Path mWifiRunningPath = new Path();
final Path mWakeLockPath = new Path();
int mFontSize;
BatteryStats mStats;
long mStatsPeriod;
String mDurationString;
String mTotalDurationString;
String mChargingLabel;
String mScreenOnLabel;
String mGpsOnLabel;
String mWifiRunningLabel;
String mWakeLockLabel;
String mPhoneSignalLabel;
int mTextAscent;
int mTextDescent;
int mDurationStringWidth;
int mTotalDurationStringWidth;
boolean mLargeMode;
int mLineWidth;
int mThinLineWidth;
int mChargingOffset;
int mScreenOnOffset;
int mGpsOnOffset;
int mWifiRunningOffset;
int mWakeLockOffset;
int mPhoneSignalOffset;
int mLevelOffset;
int mLevelTop;
int mLevelBottom;
static final int PHONE_SIGNAL_X_MASK = 0x0000ffff;
static final int PHONE_SIGNAL_BIN_MASK = 0xffff0000;
static final int PHONE_SIGNAL_BIN_SHIFT = 16;
int mNumPhoneSignalTicks;
int[] mPhoneSignalTicks;
int mNumHist;
BatteryStats.HistoryItem mHistFirst;
long mHistStart;
long mHistEnd;
int mBatLow;
int mBatHigh;
boolean mHaveWifi;
boolean mHaveGps;
public BatteryHistoryChart(Context context, AttributeSet attrs) {
super(context, attrs);
mBatteryBackgroundPaint.setARGB(255, 128, 128, 128);
mBatteryBackgroundPaint.setStyle(Paint.Style.FILL);
mBatteryGoodPaint.setARGB(128, 0, 255, 0);
mBatteryGoodPaint.setStyle(Paint.Style.STROKE);
mBatteryWarnPaint.setARGB(128, 255, 255, 0);
mBatteryWarnPaint.setStyle(Paint.Style.STROKE);
mBatteryCriticalPaint.setARGB(192, 255, 0, 0);
mBatteryCriticalPaint.setStyle(Paint.Style.STROKE);
mChargingPaint.setARGB(255, 0, 128, 0);
mChargingPaint.setStyle(Paint.Style.STROKE);
mScreenOnPaint.setARGB(255, 0, 0, 255);
mScreenOnPaint.setStyle(Paint.Style.STROKE);
mGpsOnPaint.setARGB(255, 0, 0, 255);
mGpsOnPaint.setStyle(Paint.Style.STROKE);
mWifiRunningPaint.setARGB(255, 0, 0, 255);
mWifiRunningPaint.setStyle(Paint.Style.STROKE);
mWakeLockPaint.setARGB(255, 0, 0, 255);
mWakeLockPaint.setStyle(Paint.Style.STROKE);
for (int i=0; i<NUM_PHONE_SIGNALS; i++) {
mPhoneSignalPaints[i] = new Paint();
mPhoneSignalPaints[i].setColor(mPhoneSignalColors[i]);
mPhoneSignalPaints[i].setStyle(Paint.Style.FILL);
}
mTextPaint.density = getResources().getDisplayMetrics().density;
mTextPaint.setCompatibilityScaling(
getResources().getCompatibilityInfo().applicationScale);
TypedArray a =
context.obtainStyledAttributes(
attrs, R.styleable.BatteryHistoryChart, 0, 0);
ColorStateList textColor = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;
TypedArray appearance = null;
int ap = a.getResourceId(R.styleable.BatteryHistoryChart_android_textAppearance, -1);
if (ap != -1) {
appearance = context.obtainStyledAttributes(ap,
com.android.internal.R.styleable.
TextAppearance);
}
if (appearance != null) {
int n = appearance.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = appearance.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.TextAppearance_textColor:
textColor = appearance.getColorStateList(attr);
break;
case com.android.internal.R.styleable.TextAppearance_textSize:
textSize = appearance.getDimensionPixelSize(attr, textSize);
break;
case com.android.internal.R.styleable.TextAppearance_typeface:
typefaceIndex = appearance.getInt(attr, -1);
break;
case com.android.internal.R.styleable.TextAppearance_textStyle:
styleIndex = appearance.getInt(attr, -1);
break;
}
}
appearance.recycle();
}
int shadowcolor = 0;
float dx=0, dy=0, r=0;
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.BatteryHistoryChart_android_shadowColor:
shadowcolor = a.getInt(attr, 0);
break;
case R.styleable.BatteryHistoryChart_android_shadowDx:
dx = a.getFloat(attr, 0);
break;
case R.styleable.BatteryHistoryChart_android_shadowDy:
dy = a.getFloat(attr, 0);
break;
case R.styleable.BatteryHistoryChart_android_shadowRadius:
r = a.getFloat(attr, 0);
break;
case R.styleable.BatteryHistoryChart_android_textColor:
textColor = a.getColorStateList(attr);
break;
case R.styleable.BatteryHistoryChart_android_textSize:
textSize = a.getDimensionPixelSize(attr, textSize);
break;
case R.styleable.BatteryHistoryChart_android_typeface:
typefaceIndex = a.getInt(attr, typefaceIndex);
break;
case R.styleable.BatteryHistoryChart_android_textStyle:
styleIndex = a.getInt(attr, styleIndex);
break;
}
}
mTextPaint.setColor(textColor.getDefaultColor());
mTextPaint.setTextSize(textSize);
Typeface tf = null;
switch (typefaceIndex) {
case SANS:
tf = Typeface.SANS_SERIF;
break;
case SERIF:
tf = Typeface.SERIF;
break;
case MONOSPACE:
tf = Typeface.MONOSPACE;
break;
}
setTypeface(tf, styleIndex);
if (shadowcolor != 0) {
mTextPaint.setShadowLayer(r, dx, dy, shadowcolor);
}
}
public void setTypeface(Typeface tf, int style) {
if (style > 0) {
if (tf == null) {
tf = Typeface.defaultFromStyle(style);
} else {
tf = Typeface.create(tf, style);
}
mTextPaint.setTypeface(tf);
// now compute what (if any) algorithmic styling is needed
int typefaceStyle = tf != null ? tf.getStyle() : 0;
int need = style & ~typefaceStyle;
mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
} else {
mTextPaint.setFakeBoldText(false);
mTextPaint.setTextSkewX(0);
mTextPaint.setTypeface(tf);
}
}
void setStats(BatteryStats stats) {
mStats = stats;
long uSecTime = mStats.computeBatteryRealtime(SystemClock.elapsedRealtime() * 1000,
BatteryStats.STATS_SINCE_CHARGED);
mStatsPeriod = uSecTime;
String durationString = Utils.formatElapsedTime(getContext(), mStatsPeriod / 1000);
mDurationString = getContext().getString(R.string.battery_stats_on_battery,
durationString);
mChargingLabel = getContext().getString(R.string.battery_stats_charging_label);
mScreenOnLabel = getContext().getString(R.string.battery_stats_screen_on_label);
mGpsOnLabel = getContext().getString(R.string.battery_stats_gps_on_label);
mWifiRunningLabel = getContext().getString(R.string.battery_stats_wifi_running_label);
mWakeLockLabel = getContext().getString(R.string.battery_stats_wake_lock_label);
mPhoneSignalLabel = getContext().getString(R.string.battery_stats_phone_signal_label);
BatteryStats.HistoryItem rec = stats.getHistory();
mHistFirst = null;
int pos = 0;
int lastInteresting = 0;
byte lastLevel = -1;
mBatLow = 0;
mBatHigh = 100;
int aggrStates = 0;
while (rec != null) {
pos++;
if (rec.cmd == HistoryItem.CMD_UPDATE) {
if (mHistFirst == null) {
mHistFirst = rec;
mHistStart = rec.time;
}
if (rec.batteryLevel != lastLevel || pos == 1) {
lastLevel = rec.batteryLevel;
lastInteresting = pos;
mHistEnd = rec.time;
}
aggrStates |= rec.states;
}
rec = rec.next;
}
mNumHist = lastInteresting;
mHaveGps = (aggrStates&HistoryItem.STATE_GPS_ON_FLAG) != 0;
mHaveWifi = (aggrStates&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0;
if (mHistEnd <= mHistStart) mHistEnd = mHistStart+1;
mTotalDurationString = Utils.formatElapsedTime(getContext(), mHistEnd - mHistStart);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mDurationStringWidth = (int)mTextPaint.measureText(mDurationString);
mTotalDurationStringWidth = (int)mTextPaint.measureText(mTotalDurationString);
mTextAscent = (int)mTextPaint.ascent();
mTextDescent = (int)mTextPaint.descent();
}
void addPhoneSignalTick(int x, int bin) {
mPhoneSignalTicks[mNumPhoneSignalTicks]
= x | bin << PHONE_SIGNAL_BIN_SHIFT;
mNumPhoneSignalTicks++;
}
void finishPaths(int w, int h, int levelh, int startX, int y, Path curLevelPath,
int lastX, boolean lastCharging, boolean lastScreenOn, boolean lastGpsOn,
boolean lastWifiRunning, boolean lastWakeLock, int lastPhoneSignal, Path lastPath) {
if (curLevelPath != null) {
if (lastX >= 0 && lastX < w) {
if (lastPath != null) {
lastPath.lineTo(w, y);
}
curLevelPath.lineTo(w, y);
}
curLevelPath.lineTo(w, mLevelTop+levelh);
curLevelPath.lineTo(startX, mLevelTop+levelh);
curLevelPath.close();
}
if (lastCharging) {
mChargingPath.lineTo(w, h-mChargingOffset);
}
if (lastScreenOn) {
mScreenOnPath.lineTo(w, h-mScreenOnOffset);
}
if (lastGpsOn) {
mGpsOnPath.lineTo(w, h-mGpsOnOffset);
}
if (lastWifiRunning) {
mWifiRunningPath.lineTo(w, h-mWifiRunningOffset);
}
if (lastWakeLock) {
mWakeLockPath.lineTo(w, h-mWakeLockOffset);
}
if (lastPhoneSignal != 0) {
addPhoneSignalTick(w, 0);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int textHeight = mTextDescent - mTextAscent;
mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2, getResources().getDisplayMetrics());
if (h > (textHeight*6)) {
mLargeMode = true;
mLineWidth = textHeight/2;
mLevelTop = textHeight + mLineWidth;
} else {
mLargeMode = false;
mLineWidth = mThinLineWidth;
mLevelTop = 0;
}
if (mLineWidth <= 0) mLineWidth = 1;
mTextPaint.setStrokeWidth(mThinLineWidth);
mBatteryGoodPaint.setStrokeWidth(mThinLineWidth);
mBatteryWarnPaint.setStrokeWidth(mThinLineWidth);
mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth);
mChargingPaint.setStrokeWidth(mLineWidth);
mScreenOnPaint.setStrokeWidth(mLineWidth);
mGpsOnPaint.setStrokeWidth(mLineWidth);
mWifiRunningPaint.setStrokeWidth(mLineWidth);
mWakeLockPaint.setStrokeWidth(mLineWidth);
if (mLargeMode) {
int barOffset = textHeight + mLineWidth;
mChargingOffset = mLineWidth;
mScreenOnOffset = mChargingOffset + barOffset;
mWakeLockOffset = mScreenOnOffset + barOffset;
mWifiRunningOffset = mWakeLockOffset + barOffset;
- mGpsOnOffset = mHaveWifi ? (mWifiRunningOffset + barOffset) : mWakeLockOffset;
- mPhoneSignalOffset = mHaveGps ? (mGpsOnOffset + barOffset) : mWifiRunningOffset;
+ mGpsOnOffset = mWifiRunningOffset + (mHaveWifi ? barOffset : 0);
+ mPhoneSignalOffset = mGpsOnOffset + (mHaveGps ? barOffset : 0);
mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth;
mPhoneSignalTicks = new int[w+2];
} else {
mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset
= mWakeLockOffset = mLineWidth;
mChargingOffset = mLineWidth*2;
mPhoneSignalOffset = 0;
mLevelOffset = mLineWidth*3;
mPhoneSignalTicks = null;
}
mBatLevelPath.reset();
mBatGoodPath.reset();
mBatWarnPath.reset();
mBatCriticalPath.reset();
mScreenOnPath.reset();
mGpsOnPath.reset();
mWifiRunningPath.reset();
mWakeLockPath.reset();
mChargingPath.reset();
final long timeStart = mHistStart;
final long timeChange = mHistEnd-mHistStart;
final int batLow = mBatLow;
final int batChange = mBatHigh-mBatLow;
final int levelh = h - mLevelOffset - mLevelTop;
mLevelBottom = mLevelTop + levelh;
BatteryStats.HistoryItem rec = mHistFirst;
int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1;
int i = 0;
Path curLevelPath = null;
Path lastLinePath = null;
boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false;
boolean lastWifiRunning = false, lastWakeLock = false;
int lastPhoneSignalBin = 0;
final int N = mNumHist;
while (rec != null && i < N) {
if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) {
x = (int)(((rec.time-timeStart)*w)/timeChange);
y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange;
if (lastX != x) {
// We have moved by at least a pixel.
if (lastY != y) {
// Don't plot changes within a pixel.
Path path;
byte value = rec.batteryLevel;
if (value <= BATTERY_CRITICAL) path = mBatCriticalPath;
else if (value <= BATTERY_WARN) path = mBatWarnPath;
else path = mBatGoodPath;
if (path != lastLinePath) {
if (lastLinePath != null) {
lastLinePath.lineTo(x, y);
}
path.moveTo(x, y);
lastLinePath = path;
} else {
path.lineTo(x, y);
}
if (curLevelPath == null) {
curLevelPath = mBatLevelPath;
curLevelPath.moveTo(x, y);
startX = x;
} else {
curLevelPath.lineTo(x, y);
}
lastX = x;
lastY = y;
}
final boolean charging =
(rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0;
if (charging != lastCharging) {
if (charging) {
mChargingPath.moveTo(x, h-mChargingOffset);
} else {
mChargingPath.lineTo(x, h-mChargingOffset);
}
lastCharging = charging;
}
final boolean screenOn =
(rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0;
if (screenOn != lastScreenOn) {
if (screenOn) {
mScreenOnPath.moveTo(x, h-mScreenOnOffset);
} else {
mScreenOnPath.lineTo(x, h-mScreenOnOffset);
}
lastScreenOn = screenOn;
}
final boolean gpsOn =
(rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0;
if (gpsOn != lastGpsOn) {
if (gpsOn) {
mGpsOnPath.moveTo(x, h-mGpsOnOffset);
} else {
mGpsOnPath.lineTo(x, h-mGpsOnOffset);
}
lastGpsOn = gpsOn;
}
final boolean wifiRunning =
(rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0;
if (wifiRunning != lastWifiRunning) {
if (wifiRunning) {
mWifiRunningPath.moveTo(x, h-mWifiRunningOffset);
} else {
mWifiRunningPath.lineTo(x, h-mWifiRunningOffset);
}
lastWifiRunning = wifiRunning;
}
final boolean wakeLock =
(rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0;
if (wakeLock != lastWakeLock) {
if (wakeLock) {
mWakeLockPath.moveTo(x, h-mWakeLockOffset);
} else {
mWakeLockPath.lineTo(x, h-mWakeLockOffset);
}
lastWakeLock = wakeLock;
}
if (mLargeMode) {
int bin;
if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK)
>> HistoryItem.STATE_PHONE_STATE_SHIFT)
== ServiceState.STATE_POWER_OFF) {
bin = 0;
} else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) {
bin = 1;
} else {
bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK)
>> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT;
bin += 2;
}
if (bin != lastPhoneSignalBin) {
addPhoneSignalTick(x, bin);
lastPhoneSignalBin = bin;
}
}
}
} else if (curLevelPath != null) {
finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
lastX = lastY = -1;
curLevelPath = null;
lastLinePath = null;
lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false;
lastPhoneSignalBin = 0;
}
rec = rec.next;
i++;
}
finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int width = getWidth();
final int height = getHeight();
canvas.drawPath(mBatLevelPath, mBatteryBackgroundPaint);
if (mLargeMode) {
canvas.drawText(mDurationString, 0, -mTextAscent + (mLineWidth/2),
mTextPaint);
canvas.drawText(mTotalDurationString, (width/2) - (mTotalDurationStringWidth/2),
mLevelBottom - mTextAscent + mThinLineWidth, mTextPaint);
} else {
canvas.drawText(mDurationString, (width/2) - (mDurationStringWidth/2),
(height/2) - ((mTextDescent-mTextAscent)/2) - mTextAscent, mTextPaint);
}
if (!mBatGoodPath.isEmpty()) {
canvas.drawPath(mBatGoodPath, mBatteryGoodPaint);
}
if (!mBatWarnPath.isEmpty()) {
canvas.drawPath(mBatWarnPath, mBatteryWarnPaint);
}
if (!mBatCriticalPath.isEmpty()) {
canvas.drawPath(mBatCriticalPath, mBatteryCriticalPaint);
}
int lastBin=0, lastX=0;
int top = height-mPhoneSignalOffset - (mLineWidth/2);
int bottom = top + mLineWidth;
for (int i=0; i<mNumPhoneSignalTicks; i++) {
int tick = mPhoneSignalTicks[i];
int x = tick&PHONE_SIGNAL_X_MASK;
int bin = (tick&PHONE_SIGNAL_BIN_MASK) >> PHONE_SIGNAL_BIN_SHIFT;
if (lastBin != 0) {
canvas.drawRect(lastX, top, x, bottom, mPhoneSignalPaints[lastBin]);
}
lastBin = bin;
lastX = x;
}
if (!mScreenOnPath.isEmpty()) {
canvas.drawPath(mScreenOnPath, mScreenOnPaint);
}
if (!mChargingPath.isEmpty()) {
canvas.drawPath(mChargingPath, mChargingPaint);
}
if (mHaveGps) {
if (!mGpsOnPath.isEmpty()) {
canvas.drawPath(mGpsOnPath, mGpsOnPaint);
}
}
if (mHaveWifi) {
if (!mWifiRunningPath.isEmpty()) {
canvas.drawPath(mWifiRunningPath, mWifiRunningPaint);
}
}
if (!mWakeLockPath.isEmpty()) {
canvas.drawPath(mWakeLockPath, mWakeLockPaint);
}
if (mLargeMode) {
canvas.drawText(mPhoneSignalLabel, 0,
height - mPhoneSignalOffset - mTextDescent, mTextPaint);
if (mHaveGps) {
canvas.drawText(mGpsOnLabel, 0,
height - mGpsOnOffset - mTextDescent, mTextPaint);
}
if (mHaveWifi) {
canvas.drawText(mWifiRunningLabel, 0,
height - mWifiRunningOffset - mTextDescent, mTextPaint);
}
canvas.drawText(mWakeLockLabel, 0,
height - mWakeLockOffset - mTextDescent, mTextPaint);
canvas.drawText(mChargingLabel, 0,
height - mChargingOffset - mTextDescent, mTextPaint);
canvas.drawText(mScreenOnLabel, 0,
height - mScreenOnOffset - mTextDescent, mTextPaint);
canvas.drawLine(0, mLevelBottom+(mThinLineWidth/2), width,
mLevelBottom+(mThinLineWidth/2), mTextPaint);
canvas.drawLine(0, mLevelTop, 0,
mLevelBottom+(mThinLineWidth/2), mTextPaint);
for (int i=0; i<10; i++) {
int y = mLevelTop + ((mLevelBottom-mLevelTop)*i)/10;
canvas.drawLine(0, y, mThinLineWidth*2, y, mTextPaint);
}
}
}
}
| true | true | protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int textHeight = mTextDescent - mTextAscent;
mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2, getResources().getDisplayMetrics());
if (h > (textHeight*6)) {
mLargeMode = true;
mLineWidth = textHeight/2;
mLevelTop = textHeight + mLineWidth;
} else {
mLargeMode = false;
mLineWidth = mThinLineWidth;
mLevelTop = 0;
}
if (mLineWidth <= 0) mLineWidth = 1;
mTextPaint.setStrokeWidth(mThinLineWidth);
mBatteryGoodPaint.setStrokeWidth(mThinLineWidth);
mBatteryWarnPaint.setStrokeWidth(mThinLineWidth);
mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth);
mChargingPaint.setStrokeWidth(mLineWidth);
mScreenOnPaint.setStrokeWidth(mLineWidth);
mGpsOnPaint.setStrokeWidth(mLineWidth);
mWifiRunningPaint.setStrokeWidth(mLineWidth);
mWakeLockPaint.setStrokeWidth(mLineWidth);
if (mLargeMode) {
int barOffset = textHeight + mLineWidth;
mChargingOffset = mLineWidth;
mScreenOnOffset = mChargingOffset + barOffset;
mWakeLockOffset = mScreenOnOffset + barOffset;
mWifiRunningOffset = mWakeLockOffset + barOffset;
mGpsOnOffset = mHaveWifi ? (mWifiRunningOffset + barOffset) : mWakeLockOffset;
mPhoneSignalOffset = mHaveGps ? (mGpsOnOffset + barOffset) : mWifiRunningOffset;
mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth;
mPhoneSignalTicks = new int[w+2];
} else {
mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset
= mWakeLockOffset = mLineWidth;
mChargingOffset = mLineWidth*2;
mPhoneSignalOffset = 0;
mLevelOffset = mLineWidth*3;
mPhoneSignalTicks = null;
}
mBatLevelPath.reset();
mBatGoodPath.reset();
mBatWarnPath.reset();
mBatCriticalPath.reset();
mScreenOnPath.reset();
mGpsOnPath.reset();
mWifiRunningPath.reset();
mWakeLockPath.reset();
mChargingPath.reset();
final long timeStart = mHistStart;
final long timeChange = mHistEnd-mHistStart;
final int batLow = mBatLow;
final int batChange = mBatHigh-mBatLow;
final int levelh = h - mLevelOffset - mLevelTop;
mLevelBottom = mLevelTop + levelh;
BatteryStats.HistoryItem rec = mHistFirst;
int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1;
int i = 0;
Path curLevelPath = null;
Path lastLinePath = null;
boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false;
boolean lastWifiRunning = false, lastWakeLock = false;
int lastPhoneSignalBin = 0;
final int N = mNumHist;
while (rec != null && i < N) {
if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) {
x = (int)(((rec.time-timeStart)*w)/timeChange);
y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange;
if (lastX != x) {
// We have moved by at least a pixel.
if (lastY != y) {
// Don't plot changes within a pixel.
Path path;
byte value = rec.batteryLevel;
if (value <= BATTERY_CRITICAL) path = mBatCriticalPath;
else if (value <= BATTERY_WARN) path = mBatWarnPath;
else path = mBatGoodPath;
if (path != lastLinePath) {
if (lastLinePath != null) {
lastLinePath.lineTo(x, y);
}
path.moveTo(x, y);
lastLinePath = path;
} else {
path.lineTo(x, y);
}
if (curLevelPath == null) {
curLevelPath = mBatLevelPath;
curLevelPath.moveTo(x, y);
startX = x;
} else {
curLevelPath.lineTo(x, y);
}
lastX = x;
lastY = y;
}
final boolean charging =
(rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0;
if (charging != lastCharging) {
if (charging) {
mChargingPath.moveTo(x, h-mChargingOffset);
} else {
mChargingPath.lineTo(x, h-mChargingOffset);
}
lastCharging = charging;
}
final boolean screenOn =
(rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0;
if (screenOn != lastScreenOn) {
if (screenOn) {
mScreenOnPath.moveTo(x, h-mScreenOnOffset);
} else {
mScreenOnPath.lineTo(x, h-mScreenOnOffset);
}
lastScreenOn = screenOn;
}
final boolean gpsOn =
(rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0;
if (gpsOn != lastGpsOn) {
if (gpsOn) {
mGpsOnPath.moveTo(x, h-mGpsOnOffset);
} else {
mGpsOnPath.lineTo(x, h-mGpsOnOffset);
}
lastGpsOn = gpsOn;
}
final boolean wifiRunning =
(rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0;
if (wifiRunning != lastWifiRunning) {
if (wifiRunning) {
mWifiRunningPath.moveTo(x, h-mWifiRunningOffset);
} else {
mWifiRunningPath.lineTo(x, h-mWifiRunningOffset);
}
lastWifiRunning = wifiRunning;
}
final boolean wakeLock =
(rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0;
if (wakeLock != lastWakeLock) {
if (wakeLock) {
mWakeLockPath.moveTo(x, h-mWakeLockOffset);
} else {
mWakeLockPath.lineTo(x, h-mWakeLockOffset);
}
lastWakeLock = wakeLock;
}
if (mLargeMode) {
int bin;
if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK)
>> HistoryItem.STATE_PHONE_STATE_SHIFT)
== ServiceState.STATE_POWER_OFF) {
bin = 0;
} else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) {
bin = 1;
} else {
bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK)
>> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT;
bin += 2;
}
if (bin != lastPhoneSignalBin) {
addPhoneSignalTick(x, bin);
lastPhoneSignalBin = bin;
}
}
}
} else if (curLevelPath != null) {
finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
lastX = lastY = -1;
curLevelPath = null;
lastLinePath = null;
lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false;
lastPhoneSignalBin = 0;
}
rec = rec.next;
i++;
}
finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
}
| protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int textHeight = mTextDescent - mTextAscent;
mThinLineWidth = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2, getResources().getDisplayMetrics());
if (h > (textHeight*6)) {
mLargeMode = true;
mLineWidth = textHeight/2;
mLevelTop = textHeight + mLineWidth;
} else {
mLargeMode = false;
mLineWidth = mThinLineWidth;
mLevelTop = 0;
}
if (mLineWidth <= 0) mLineWidth = 1;
mTextPaint.setStrokeWidth(mThinLineWidth);
mBatteryGoodPaint.setStrokeWidth(mThinLineWidth);
mBatteryWarnPaint.setStrokeWidth(mThinLineWidth);
mBatteryCriticalPaint.setStrokeWidth(mThinLineWidth);
mChargingPaint.setStrokeWidth(mLineWidth);
mScreenOnPaint.setStrokeWidth(mLineWidth);
mGpsOnPaint.setStrokeWidth(mLineWidth);
mWifiRunningPaint.setStrokeWidth(mLineWidth);
mWakeLockPaint.setStrokeWidth(mLineWidth);
if (mLargeMode) {
int barOffset = textHeight + mLineWidth;
mChargingOffset = mLineWidth;
mScreenOnOffset = mChargingOffset + barOffset;
mWakeLockOffset = mScreenOnOffset + barOffset;
mWifiRunningOffset = mWakeLockOffset + barOffset;
mGpsOnOffset = mWifiRunningOffset + (mHaveWifi ? barOffset : 0);
mPhoneSignalOffset = mGpsOnOffset + (mHaveGps ? barOffset : 0);
mLevelOffset = mPhoneSignalOffset + barOffset + mLineWidth;
mPhoneSignalTicks = new int[w+2];
} else {
mScreenOnOffset = mGpsOnOffset = mWifiRunningOffset
= mWakeLockOffset = mLineWidth;
mChargingOffset = mLineWidth*2;
mPhoneSignalOffset = 0;
mLevelOffset = mLineWidth*3;
mPhoneSignalTicks = null;
}
mBatLevelPath.reset();
mBatGoodPath.reset();
mBatWarnPath.reset();
mBatCriticalPath.reset();
mScreenOnPath.reset();
mGpsOnPath.reset();
mWifiRunningPath.reset();
mWakeLockPath.reset();
mChargingPath.reset();
final long timeStart = mHistStart;
final long timeChange = mHistEnd-mHistStart;
final int batLow = mBatLow;
final int batChange = mBatHigh-mBatLow;
final int levelh = h - mLevelOffset - mLevelTop;
mLevelBottom = mLevelTop + levelh;
BatteryStats.HistoryItem rec = mHistFirst;
int x = 0, y = 0, startX = 0, lastX = -1, lastY = -1;
int i = 0;
Path curLevelPath = null;
Path lastLinePath = null;
boolean lastCharging = false, lastScreenOn = false, lastGpsOn = false;
boolean lastWifiRunning = false, lastWakeLock = false;
int lastPhoneSignalBin = 0;
final int N = mNumHist;
while (rec != null && i < N) {
if (rec.cmd == BatteryStats.HistoryItem.CMD_UPDATE) {
x = (int)(((rec.time-timeStart)*w)/timeChange);
y = mLevelTop + levelh - ((rec.batteryLevel-batLow)*(levelh-1))/batChange;
if (lastX != x) {
// We have moved by at least a pixel.
if (lastY != y) {
// Don't plot changes within a pixel.
Path path;
byte value = rec.batteryLevel;
if (value <= BATTERY_CRITICAL) path = mBatCriticalPath;
else if (value <= BATTERY_WARN) path = mBatWarnPath;
else path = mBatGoodPath;
if (path != lastLinePath) {
if (lastLinePath != null) {
lastLinePath.lineTo(x, y);
}
path.moveTo(x, y);
lastLinePath = path;
} else {
path.lineTo(x, y);
}
if (curLevelPath == null) {
curLevelPath = mBatLevelPath;
curLevelPath.moveTo(x, y);
startX = x;
} else {
curLevelPath.lineTo(x, y);
}
lastX = x;
lastY = y;
}
final boolean charging =
(rec.states&HistoryItem.STATE_BATTERY_PLUGGED_FLAG) != 0;
if (charging != lastCharging) {
if (charging) {
mChargingPath.moveTo(x, h-mChargingOffset);
} else {
mChargingPath.lineTo(x, h-mChargingOffset);
}
lastCharging = charging;
}
final boolean screenOn =
(rec.states&HistoryItem.STATE_SCREEN_ON_FLAG) != 0;
if (screenOn != lastScreenOn) {
if (screenOn) {
mScreenOnPath.moveTo(x, h-mScreenOnOffset);
} else {
mScreenOnPath.lineTo(x, h-mScreenOnOffset);
}
lastScreenOn = screenOn;
}
final boolean gpsOn =
(rec.states&HistoryItem.STATE_GPS_ON_FLAG) != 0;
if (gpsOn != lastGpsOn) {
if (gpsOn) {
mGpsOnPath.moveTo(x, h-mGpsOnOffset);
} else {
mGpsOnPath.lineTo(x, h-mGpsOnOffset);
}
lastGpsOn = gpsOn;
}
final boolean wifiRunning =
(rec.states&HistoryItem.STATE_WIFI_RUNNING_FLAG) != 0;
if (wifiRunning != lastWifiRunning) {
if (wifiRunning) {
mWifiRunningPath.moveTo(x, h-mWifiRunningOffset);
} else {
mWifiRunningPath.lineTo(x, h-mWifiRunningOffset);
}
lastWifiRunning = wifiRunning;
}
final boolean wakeLock =
(rec.states&HistoryItem.STATE_WAKE_LOCK_FLAG) != 0;
if (wakeLock != lastWakeLock) {
if (wakeLock) {
mWakeLockPath.moveTo(x, h-mWakeLockOffset);
} else {
mWakeLockPath.lineTo(x, h-mWakeLockOffset);
}
lastWakeLock = wakeLock;
}
if (mLargeMode) {
int bin;
if (((rec.states&HistoryItem.STATE_PHONE_STATE_MASK)
>> HistoryItem.STATE_PHONE_STATE_SHIFT)
== ServiceState.STATE_POWER_OFF) {
bin = 0;
} else if ((rec.states&HistoryItem.STATE_PHONE_SCANNING_FLAG) != 0) {
bin = 1;
} else {
bin = (rec.states&HistoryItem.STATE_SIGNAL_STRENGTH_MASK)
>> HistoryItem.STATE_SIGNAL_STRENGTH_SHIFT;
bin += 2;
}
if (bin != lastPhoneSignalBin) {
addPhoneSignalTick(x, bin);
lastPhoneSignalBin = bin;
}
}
}
} else if (curLevelPath != null) {
finishPaths(x+1, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
lastX = lastY = -1;
curLevelPath = null;
lastLinePath = null;
lastCharging = lastScreenOn = lastGpsOn = lastWakeLock = false;
lastPhoneSignalBin = 0;
}
rec = rec.next;
i++;
}
finishPaths(w, h, levelh, startX, lastY, curLevelPath, lastX,
lastCharging, lastScreenOn, lastGpsOn, lastWifiRunning,
lastWakeLock, lastPhoneSignalBin, lastLinePath);
}
|
diff --git a/lab5/src/map/SimpleHashMap.java b/lab5/src/map/SimpleHashMap.java
index d86bd2d..9493bdc 100644
--- a/lab5/src/map/SimpleHashMap.java
+++ b/lab5/src/map/SimpleHashMap.java
@@ -1,228 +1,228 @@
package map;
import java.util.Iterator;
public class SimpleHashMap<K,V> implements Map<K,V> {
public static final int INITIAL_CAPACITY = 16;
public static final double MAX_LOAD_FACTOR = 0.75;
private Entry<K,V>[] table;
private int size;
/** Constructs an empty hashmap with the default initial capacity (16)
* and the default load factor (0.75). */
public SimpleHashMap() {
table = createTable(INITIAL_CAPACITY);
size = 0;
}
/** Constructs an empty hashmap with the specified initial capacity
* and the default load factor (0.75). */
public SimpleHashMap(int capacity) {
table = createTable(capacity);
}
@Override
public V get(Object arg0) {
if(arg0 == null){
throw new NullPointerException();
}
K k = (K)arg0;
Entry<K,V> e = find(index(k),k);
if(e == null){
return null;
}else {
return e.value;
}
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public V put(K k, V v) { //TODO: FIX!
if(k == null){
throw new NullPointerException();
}
int i = index(k);
Entry<K,V> e = find(i,k);
V old = null;
if(e == null){
e = new Entry<K,V>(k,v);
insert(e,i,table);
size++;
rehashIfNeeded();
}else{
old = e.getValue();
e.setValue(v);
}
return old;
}
@Override
public V remove(Object arg0) {
if (arg0 == null) {
throw new NullPointerException();
}
K k = (K)arg0;
int i = index(k);
LinkIterator itr = new LinkIterator(i);
if (itr.hasNext()) {
Entry<K,V> prev = itr.next();
if (prev.key.equals(k)) {
table[i] = prev.next;
size--;
return prev.value;
}
while (itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key.equals(k)) {
prev.next = e.next;
size--;
return e.value;
}
+ prev = e;
}
}
- //rehashIfNeeded();
return null;
}
@Override
public int size() {
return size;
}
public String show(){
StringBuilder sb = new StringBuilder();
for(int i=0; i < table.length; i++){
sb.append(i);
sb.append("\t");
LinkIterator itr = new LinkIterator(i);
while(itr.hasNext()){
Entry<K,V> e = itr.next();
sb.append(" " + e.toString());
}
sb.append("\n");
}
return sb.toString();
}
private int index(K key) {
return index(key,table.length);
}
private int index(K key, int length){
return Math.abs(key.hashCode()) % length;
}
private Entry<K,V> find(int index, K key) {
LinkIterator itr = new LinkIterator(index);
while(itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key.equals(key)) {
return e;
}
}
return null;
}
private void rehashIfNeeded(){
if(size < MAX_LOAD_FACTOR*table.length){//TODO! make smaller?
return;
}
int newLength = table.length*2;
Entry<K,V>[] newTable = createTable(newLength);
int check_size = 0;
for(int i=0; i< table.length; i++){
LinkIterator itr = new LinkIterator(i);
while(itr.hasNext()){
Entry<K,V> e = itr.next();
e.next = null;
insert(e,index(e.key,newLength),newTable);
check_size++;
}
}
table = newTable;
}
private void insert(Entry<K,V> e, int i, Entry<K,V>[] table){
if(table[i] != null){
e.next = table[i];
}
table[i] = e;
}
@SuppressWarnings("unchecked")
private Entry<K,V>[] createTable(int size){
return (Entry<K,V>[]) new Entry[size];
}
private static class Entry<K,V> implements Map.Entry<K,V> {
private K key;
private V value;
private Entry<K,V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
public String toString() {
return key.toString() + "=" + value.toString();
}
}
private class LinkIterator implements Iterator<Entry<K,V>>{
private Entry<K,V> next;
public LinkIterator(int index){
next = table[index];
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Entry<K,V> next() {
if(!hasNext()){
return null;
}
Entry<K,V> next = this.next;
this.next = this.next.next;
return next;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| false | true | public V remove(Object arg0) {
if (arg0 == null) {
throw new NullPointerException();
}
K k = (K)arg0;
int i = index(k);
LinkIterator itr = new LinkIterator(i);
if (itr.hasNext()) {
Entry<K,V> prev = itr.next();
if (prev.key.equals(k)) {
table[i] = prev.next;
size--;
return prev.value;
}
while (itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key.equals(k)) {
prev.next = e.next;
size--;
return e.value;
}
}
}
//rehashIfNeeded();
return null;
}
| public V remove(Object arg0) {
if (arg0 == null) {
throw new NullPointerException();
}
K k = (K)arg0;
int i = index(k);
LinkIterator itr = new LinkIterator(i);
if (itr.hasNext()) {
Entry<K,V> prev = itr.next();
if (prev.key.equals(k)) {
table[i] = prev.next;
size--;
return prev.value;
}
while (itr.hasNext()) {
Entry<K,V> e = itr.next();
if (e.key.equals(k)) {
prev.next = e.next;
size--;
return e.value;
}
prev = e;
}
}
return null;
}
|
diff --git a/src/com/vaadin/demo/featurebrowser/TableExample.java b/src/com/vaadin/demo/featurebrowser/TableExample.java
index f1dfc1f18..1c9ac6c2d 100644
--- a/src/com/vaadin/demo/featurebrowser/TableExample.java
+++ b/src/com/vaadin/demo/featurebrowser/TableExample.java
@@ -1,298 +1,298 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.demo.featurebrowser;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.event.Action;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
/**
* Table example.
*
* @author IT Mill Ltd.
*/
public class TableExample extends CustomComponent implements Action.Handler,
Button.ClickListener {
// Actions
private static final Action ACTION_SAVE = new Action("Save");
private static final Action ACTION_DELETE = new Action("Delete");
private static final Action ACTION_HIRE = new Action("Hire");
// Action sets
private static final Action[] ACTIONS_NOHIRE = new Action[] { ACTION_SAVE,
ACTION_DELETE };
private static final Action[] ACTIONS_HIRE = new Action[] { ACTION_HIRE,
ACTION_SAVE, ACTION_DELETE };
// Properties
private static final Object PROPERTY_SPECIES = "Species";
private static final Object PROPERTY_TYPE = "Type";
private static final Object PROPERTY_KIND = "Kind";
private static final Object PROPERTY_HIRED = "Hired";
// "global" components
Table source;
Table saved;
Button saveSelected;
Button hireSelected;
Button deleteSelected;
Button deselect;
public TableExample() {
VerticalLayout margin = new VerticalLayout();
margin.setMargin(true);
TabSheet root = new TabSheet();
setCompositionRoot(margin);
margin.addComponent(root);
// main layout
final VerticalLayout main = new VerticalLayout();
- root.addComponent(main);
main.setCaption("Basic Table");
main.setMargin(true);
+ root.addTab(main);
// "source" table with bells & whistlesenabled
source = new Table("All creatures");
source.setPageLength(7);
source.setWidth("550px");
source.setColumnCollapsingAllowed(true);
source.setColumnReorderingAllowed(true);
source.setSelectable(true);
source.setMultiSelect(true);
source.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
fillTable(source);
source.addActionHandler(this);
main.addComponent(source);
// x-selected button row
final HorizontalLayout horiz = new HorizontalLayout();
horiz.setMargin(false, false, true, false);
main.addComponent(horiz);
saveSelected = new Button("Save selected");
saveSelected.setStyleName(Button.STYLE_LINK);
saveSelected.addListener(this);
horiz.addComponent(saveSelected);
hireSelected = new Button("Hire selected");
hireSelected.setStyleName(Button.STYLE_LINK);
hireSelected.addListener(this);
horiz.addComponent(hireSelected);
deleteSelected = new Button("Delete selected");
deleteSelected.setStyleName(Button.STYLE_LINK);
deleteSelected.addListener(this);
horiz.addComponent(deleteSelected);
deselect = new Button("Deselect all");
deselect.setStyleName(Button.STYLE_LINK);
deselect.addListener(this);
horiz.addComponent(deselect);
final CheckBox editmode = new CheckBox("Editmode ");
editmode.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
source.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
editmode.setImmediate(true);
horiz.addComponent(editmode);
// "saved" table, minimalistic
saved = new Table("Saved creatures");
saved.setPageLength(5);
saved.setWidth("550px");
saved.setSelectable(false);
saved.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
saved.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
initProperties(saved);
saved.addActionHandler(this);
main.addComponent(saved);
final CheckBox b = new CheckBox("Modify saved creatures");
b.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
saved.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
b.setImmediate(true);
main.addComponent(b);
GeneratedColumnExample gencols = new GeneratedColumnExample();
gencols.setCaption("Generated Columns");
root.addComponent(gencols);
}
// set up the properties (columns)
private void initProperties(Table table) {
table.addContainerProperty(PROPERTY_SPECIES, String.class, "");
table.addContainerProperty(PROPERTY_TYPE, String.class, "");
table.addContainerProperty(PROPERTY_KIND, String.class, "");
table
.addContainerProperty(PROPERTY_HIRED, Boolean.class,
Boolean.FALSE);
}
// fill the table with some random data
private void fillTable(Table table) {
initProperties(table);
final String[] sp = new String[] { "Fox", "Dog", "Cat", "Moose",
"Penguin", "Cow" };
final String[] ty = new String[] { "Quick", "Lazy", "Sleepy",
"Fidgety", "Crazy", "Kewl" };
final String[] ki = new String[] { "Jumping", "Walking", "Sleeping",
"Skipping", "Dancing" };
Random r = new Random(5);
for (int i = 0; i < 100; i++) {
final String s = sp[(int) (r.nextDouble() * sp.length)];
final String t = ty[(int) (r.nextDouble() * ty.length)];
final String k = ki[(int) (r.nextDouble() * ki.length)];
table.addItem(new Object[] { s, t, k, Boolean.FALSE }, new Integer(
i));
}
}
// Called for each item (row), returns valid actions for that item
public Action[] getActions(Object target, Object sender) {
if (sender == source) {
final Item item = source.getItem(target);
// save, delete, and hire if not already hired
if (item != null
&& item.getItemProperty(PROPERTY_HIRED).getValue() == Boolean.FALSE) {
return ACTIONS_HIRE;
} else {
return ACTIONS_NOHIRE;
}
} else {
// "saved" table only has one action
return new Action[] { ACTION_DELETE };
}
}
// called when an action is invoked on an item (row)
public void handleAction(Action action, Object sender, Object target) {
if (sender == source) {
Item item = source.getItem(target);
if (action == ACTION_HIRE) {
// set HIRED property to true
item.getItemProperty(PROPERTY_HIRED).setValue(Boolean.TRUE);
if (saved.containsId(target)) {
item = saved.getItem(target);
item.getItemProperty(PROPERTY_HIRED).setValue(Boolean.TRUE);
}
getWindow().showNotification("Hired", "" + item);
} else if (action == ACTION_SAVE) {
if (saved.containsId(target)) {
// let's not save twice
getWindow().showNotification("Already saved", "" + item);
return;
}
// "manual" copy of the item properties we want
final Item added = saved.addItem(target);
Property p = added.getItemProperty(PROPERTY_SPECIES);
p.setValue(item.getItemProperty(PROPERTY_SPECIES).getValue());
p = added.getItemProperty(PROPERTY_TYPE);
p.setValue(item.getItemProperty(PROPERTY_TYPE).getValue());
p = added.getItemProperty(PROPERTY_KIND);
p.setValue(item.getItemProperty(PROPERTY_KIND).getValue());
p = added.getItemProperty(PROPERTY_HIRED);
p.setValue(item.getItemProperty(PROPERTY_HIRED).getValue());
getWindow().showNotification("Saved", "" + item);
} else {
// ACTION_DELETE
getWindow().showNotification("Deleted ", "" + item);
source.removeItem(target);
}
} else {
// sender==saved
if (action == ACTION_DELETE) {
final Item item = saved.getItem(target);
getWindow().showNotification("Deleted", "" + item);
saved.removeItem(target);
}
}
}
public void buttonClick(ClickEvent event) {
final Button b = event.getButton();
if (b == deselect) {
source.setValue(null);
} else if (b == saveSelected) {
// loop each selected and copy to "saved" table
final Set selected = (Set) source.getValue();
int s = 0;
for (final Iterator it = selected.iterator(); it.hasNext();) {
final Object id = it.next();
if (!saved.containsId(id)) {
final Item item = source.getItem(id);
final Item added = saved.addItem(id);
// "manual" copy of the properties we want
Property p = added.getItemProperty(PROPERTY_SPECIES);
p.setValue(item.getItemProperty(PROPERTY_SPECIES)
.getValue());
p = added.getItemProperty(PROPERTY_TYPE);
p.setValue(item.getItemProperty(PROPERTY_TYPE).getValue());
p = added.getItemProperty(PROPERTY_KIND);
p.setValue(item.getItemProperty(PROPERTY_KIND).getValue());
p = added.getItemProperty(PROPERTY_HIRED);
p.setValue(item.getItemProperty(PROPERTY_HIRED).getValue());
s++;
}
}
getWindow().showNotification("Saved " + s);
} else if (b == hireSelected) {
// loop each selected and set property HIRED to true
int s = 0;
final Set selected = (Set) source.getValue();
for (final Iterator it = selected.iterator(); it.hasNext();) {
final Object id = it.next();
Item item = source.getItem(id);
final Property p = item.getItemProperty(PROPERTY_HIRED);
if (p.getValue() == Boolean.FALSE) {
p.setValue(Boolean.TRUE);
s++;
}
if (saved.containsId(id)) {
// also update "saved" table
item = saved.getItem(id);
item.getItemProperty(PROPERTY_HIRED).setValue(Boolean.TRUE);
}
}
getWindow().showNotification("Hired " + s);
} else {
// loop trough selected and delete
int s = 0;
final Set selected = (Set) source.getValue();
for (final Iterator it = selected.iterator(); it.hasNext();) {
final Object id = it.next();
if (source.containsId(id)) {
s++;
source.removeItem(id);
}
}
getWindow().showNotification("Deleted " + s);
}
}
}
| false | true | public TableExample() {
VerticalLayout margin = new VerticalLayout();
margin.setMargin(true);
TabSheet root = new TabSheet();
setCompositionRoot(margin);
margin.addComponent(root);
// main layout
final VerticalLayout main = new VerticalLayout();
root.addComponent(main);
main.setCaption("Basic Table");
main.setMargin(true);
// "source" table with bells & whistlesenabled
source = new Table("All creatures");
source.setPageLength(7);
source.setWidth("550px");
source.setColumnCollapsingAllowed(true);
source.setColumnReorderingAllowed(true);
source.setSelectable(true);
source.setMultiSelect(true);
source.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
fillTable(source);
source.addActionHandler(this);
main.addComponent(source);
// x-selected button row
final HorizontalLayout horiz = new HorizontalLayout();
horiz.setMargin(false, false, true, false);
main.addComponent(horiz);
saveSelected = new Button("Save selected");
saveSelected.setStyleName(Button.STYLE_LINK);
saveSelected.addListener(this);
horiz.addComponent(saveSelected);
hireSelected = new Button("Hire selected");
hireSelected.setStyleName(Button.STYLE_LINK);
hireSelected.addListener(this);
horiz.addComponent(hireSelected);
deleteSelected = new Button("Delete selected");
deleteSelected.setStyleName(Button.STYLE_LINK);
deleteSelected.addListener(this);
horiz.addComponent(deleteSelected);
deselect = new Button("Deselect all");
deselect.setStyleName(Button.STYLE_LINK);
deselect.addListener(this);
horiz.addComponent(deselect);
final CheckBox editmode = new CheckBox("Editmode ");
editmode.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
source.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
editmode.setImmediate(true);
horiz.addComponent(editmode);
// "saved" table, minimalistic
saved = new Table("Saved creatures");
saved.setPageLength(5);
saved.setWidth("550px");
saved.setSelectable(false);
saved.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
saved.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
initProperties(saved);
saved.addActionHandler(this);
main.addComponent(saved);
final CheckBox b = new CheckBox("Modify saved creatures");
b.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
saved.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
b.setImmediate(true);
main.addComponent(b);
GeneratedColumnExample gencols = new GeneratedColumnExample();
gencols.setCaption("Generated Columns");
root.addComponent(gencols);
}
| public TableExample() {
VerticalLayout margin = new VerticalLayout();
margin.setMargin(true);
TabSheet root = new TabSheet();
setCompositionRoot(margin);
margin.addComponent(root);
// main layout
final VerticalLayout main = new VerticalLayout();
main.setCaption("Basic Table");
main.setMargin(true);
root.addTab(main);
// "source" table with bells & whistlesenabled
source = new Table("All creatures");
source.setPageLength(7);
source.setWidth("550px");
source.setColumnCollapsingAllowed(true);
source.setColumnReorderingAllowed(true);
source.setSelectable(true);
source.setMultiSelect(true);
source.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
fillTable(source);
source.addActionHandler(this);
main.addComponent(source);
// x-selected button row
final HorizontalLayout horiz = new HorizontalLayout();
horiz.setMargin(false, false, true, false);
main.addComponent(horiz);
saveSelected = new Button("Save selected");
saveSelected.setStyleName(Button.STYLE_LINK);
saveSelected.addListener(this);
horiz.addComponent(saveSelected);
hireSelected = new Button("Hire selected");
hireSelected.setStyleName(Button.STYLE_LINK);
hireSelected.addListener(this);
horiz.addComponent(hireSelected);
deleteSelected = new Button("Delete selected");
deleteSelected.setStyleName(Button.STYLE_LINK);
deleteSelected.addListener(this);
horiz.addComponent(deleteSelected);
deselect = new Button("Deselect all");
deselect.setStyleName(Button.STYLE_LINK);
deselect.addListener(this);
horiz.addComponent(deselect);
final CheckBox editmode = new CheckBox("Editmode ");
editmode.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
source.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
editmode.setImmediate(true);
horiz.addComponent(editmode);
// "saved" table, minimalistic
saved = new Table("Saved creatures");
saved.setPageLength(5);
saved.setWidth("550px");
saved.setSelectable(false);
saved.setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
saved.setRowHeaderMode(Table.ROW_HEADER_MODE_ID);
initProperties(saved);
saved.addActionHandler(this);
main.addComponent(saved);
final CheckBox b = new CheckBox("Modify saved creatures");
b.addListener(new CheckBox.ClickListener() {
public void buttonClick(ClickEvent event) {
saved.setEditable(((Boolean) event.getButton().getValue())
.booleanValue());
}
});
b.setImmediate(true);
main.addComponent(b);
GeneratedColumnExample gencols = new GeneratedColumnExample();
gencols.setCaption("Generated Columns");
root.addComponent(gencols);
}
|
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/ServiceStatusUtil.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/ServiceStatusUtil.java
index 589eeadce..365eab8c1 100644
--- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/ServiceStatusUtil.java
+++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/ServiceStatusUtil.java
@@ -1,38 +1,38 @@
package org.sonatype.nexus.test.utils;
import org.sonatype.nexus.client.NexusClient;
import org.sonatype.nexus.client.NexusClientException;
import org.sonatype.nexus.client.NexusConnectionException;
import org.sonatype.nexus.client.rest.NexusRestClient;
public class ServiceStatusUtil
{
public static boolean waitForStart( NexusClient client )
throws NexusClientException, NexusConnectionException
{
System.setProperty( NexusRestClient.WAIT_FOR_START_TIMEOUT_KEY, "1000" );
- for ( int i = 0; i < 40; i++ )
+ for ( int i = 0; i < 240; i++ )
{
if ( client.isNexusStarted( true ) )
{
return true;
}
}
return false;
}
public static boolean waitForStop( NexusClient client )
throws NexusClientException, NexusConnectionException
{
System.setProperty( NexusRestClient.WAIT_FOR_START_TIMEOUT_KEY, "1000" );
for ( int i = 0; i < 240; i++ )
{
if ( !client.isNexusStarted( true ) )
{
return true;
}
}
return false;
}
}
| true | true | public static boolean waitForStart( NexusClient client )
throws NexusClientException, NexusConnectionException
{
System.setProperty( NexusRestClient.WAIT_FOR_START_TIMEOUT_KEY, "1000" );
for ( int i = 0; i < 40; i++ )
{
if ( client.isNexusStarted( true ) )
{
return true;
}
}
return false;
}
| public static boolean waitForStart( NexusClient client )
throws NexusClientException, NexusConnectionException
{
System.setProperty( NexusRestClient.WAIT_FOR_START_TIMEOUT_KEY, "1000" );
for ( int i = 0; i < 240; i++ )
{
if ( client.isNexusStarted( true ) )
{
return true;
}
}
return false;
}
|
diff --git a/ScreenManager/smanager-ui/src/main/java/com/atanor/smanager/client/ui/NavigationArea.java b/ScreenManager/smanager-ui/src/main/java/com/atanor/smanager/client/ui/NavigationArea.java
index 614159d..64d20e6 100644
--- a/ScreenManager/smanager-ui/src/main/java/com/atanor/smanager/client/ui/NavigationArea.java
+++ b/ScreenManager/smanager-ui/src/main/java/com/atanor/smanager/client/ui/NavigationArea.java
@@ -1,137 +1,137 @@
package com.atanor.smanager.client.ui;
import com.atanor.smanager.rpc.dto.HardwareDto;
import com.atanor.smanager.rpc.dto.PresetDto;
import com.atanor.smanager.rpc.dto.WindowDto;
import com.atanor.smanager.rpc.services.ConfigService;
import com.atanor.smanager.rpc.services.ConfigServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
public class NavigationArea extends HLayout {
private final ConfigServiceAsync configService = GWT
.create(ConfigService.class);
private String namePreset = "name", windowN = "window";
public NavigationArea(final SimpleEventBus bus) {
super();
this.setMembersMargin(10);
this.setOverflow(Overflow.HIDDEN);
this.setShowResizeBar(true);
final SectionStack sectionStack = new SectionStack();
sectionStack.setShowExpandControls(true);
sectionStack.setAnimateSections(true);
sectionStack.setVisibilityMode(VisibilityMode.MUTEX);
sectionStack.setOverflow(Overflow.HIDDEN);
sectionStack.setMembersMargin(5);
sectionStack.setContents("<H2>Presets</H2>");
// final SectionStackSection section1 = new
// SectionStackSection("Presets");
// section1.setMembersMargin(20);
// section1.setExpanded(true);
configService
.getHardwareConfiguration(new AsyncCallback<HardwareDto>() {
@Override
public void onSuccess(final HardwareDto result) {
int pres = 0, win = 0;
for (PresetDto preset : result.getPresets()) {
namePreset = namePreset + pres;
final Label $namePreset = new Label();
$namePreset.setTop((pres * 164) + 2);
$namePreset.setLeft(7);
$namePreset.setWidth(164);
$namePreset.setHeight(62);
$namePreset.setShowEdges(true);
$namePreset.setBorder("2px solid black");
$namePreset.setMaxWidth(164);
$namePreset.setMaxHeight(62);
$namePreset.setBackgroundColor("lightgrey");
$namePreset.setProperty("preset", pres);
$namePreset.draw();
// $namePreset
// .addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(
// DoubleClickEvent event) {
// event.getSource();
// bus.fireEvent(new AnimateEvent(0));
// for (int count = 0; count <= result
// .getPresets().size(); count++) {
// $namePreset.animateFade(30,
// null, 1000);
//// $namePreset.animateFade(100,
//// null, 1000);
// }
// }
// });
pres++;
for (WindowDto window : preset.getWindows()) {
windowN = windowN + win;
final Label $windowN = new Label();
$windowN.setTop(window.getYTopLeft() / 20);
$windowN.setLeft(window.getXTopLeft() / 10);
- $windowN.setWidth((window.getXBottomRigh() - window
+ $windowN.setWidth((window.getXBottomRight() - window
.getXTopLeft()) / 10);
$windowN.setHeight((window.getYBottomRight() - window
.getYTopLeft()) / 20);
$windowN.setBorder("1px solid black");
$windowN.setBackgroundColor("darkgrey");
$windowN.draw();
$namePreset.addChild($windowN);
win++;
}
;
sectionStack.addChild($namePreset);
}
}
@Override
public void onFailure(Throwable caught) {
SC.say("Configurations are not available!");
caught.printStackTrace();
}
});
// drawPane2.addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(DoubleClickEvent event) {
// drawPane2.animateFade(30, null, 1000);
// bus.fireEvent(new AnimateEvent(1));
// drawPane.animateFade(100, null, 1000);
// }
// });
//
// DrawLabel name1 = new DrawLabel();
// name1.setDrawPane(drawPane);
// name1.setLeft(33);
// name1.setTop(24);
// name1.setContents("One to All");
// name1.setLineWidth(1);
// name1.setFontSize(11);
// name1.draw();
// sectionStack.addSection(section1);
this.addMember(sectionStack);
}
}
| true | true | public NavigationArea(final SimpleEventBus bus) {
super();
this.setMembersMargin(10);
this.setOverflow(Overflow.HIDDEN);
this.setShowResizeBar(true);
final SectionStack sectionStack = new SectionStack();
sectionStack.setShowExpandControls(true);
sectionStack.setAnimateSections(true);
sectionStack.setVisibilityMode(VisibilityMode.MUTEX);
sectionStack.setOverflow(Overflow.HIDDEN);
sectionStack.setMembersMargin(5);
sectionStack.setContents("<H2>Presets</H2>");
// final SectionStackSection section1 = new
// SectionStackSection("Presets");
// section1.setMembersMargin(20);
// section1.setExpanded(true);
configService
.getHardwareConfiguration(new AsyncCallback<HardwareDto>() {
@Override
public void onSuccess(final HardwareDto result) {
int pres = 0, win = 0;
for (PresetDto preset : result.getPresets()) {
namePreset = namePreset + pres;
final Label $namePreset = new Label();
$namePreset.setTop((pres * 164) + 2);
$namePreset.setLeft(7);
$namePreset.setWidth(164);
$namePreset.setHeight(62);
$namePreset.setShowEdges(true);
$namePreset.setBorder("2px solid black");
$namePreset.setMaxWidth(164);
$namePreset.setMaxHeight(62);
$namePreset.setBackgroundColor("lightgrey");
$namePreset.setProperty("preset", pres);
$namePreset.draw();
// $namePreset
// .addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(
// DoubleClickEvent event) {
// event.getSource();
// bus.fireEvent(new AnimateEvent(0));
// for (int count = 0; count <= result
// .getPresets().size(); count++) {
// $namePreset.animateFade(30,
// null, 1000);
//// $namePreset.animateFade(100,
//// null, 1000);
// }
// }
// });
pres++;
for (WindowDto window : preset.getWindows()) {
windowN = windowN + win;
final Label $windowN = new Label();
$windowN.setTop(window.getYTopLeft() / 20);
$windowN.setLeft(window.getXTopLeft() / 10);
$windowN.setWidth((window.getXBottomRigh() - window
.getXTopLeft()) / 10);
$windowN.setHeight((window.getYBottomRight() - window
.getYTopLeft()) / 20);
$windowN.setBorder("1px solid black");
$windowN.setBackgroundColor("darkgrey");
$windowN.draw();
$namePreset.addChild($windowN);
win++;
}
;
sectionStack.addChild($namePreset);
}
}
@Override
public void onFailure(Throwable caught) {
SC.say("Configurations are not available!");
caught.printStackTrace();
}
});
// drawPane2.addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(DoubleClickEvent event) {
// drawPane2.animateFade(30, null, 1000);
// bus.fireEvent(new AnimateEvent(1));
// drawPane.animateFade(100, null, 1000);
// }
// });
//
// DrawLabel name1 = new DrawLabel();
// name1.setDrawPane(drawPane);
// name1.setLeft(33);
// name1.setTop(24);
// name1.setContents("One to All");
// name1.setLineWidth(1);
// name1.setFontSize(11);
// name1.draw();
// sectionStack.addSection(section1);
this.addMember(sectionStack);
}
| public NavigationArea(final SimpleEventBus bus) {
super();
this.setMembersMargin(10);
this.setOverflow(Overflow.HIDDEN);
this.setShowResizeBar(true);
final SectionStack sectionStack = new SectionStack();
sectionStack.setShowExpandControls(true);
sectionStack.setAnimateSections(true);
sectionStack.setVisibilityMode(VisibilityMode.MUTEX);
sectionStack.setOverflow(Overflow.HIDDEN);
sectionStack.setMembersMargin(5);
sectionStack.setContents("<H2>Presets</H2>");
// final SectionStackSection section1 = new
// SectionStackSection("Presets");
// section1.setMembersMargin(20);
// section1.setExpanded(true);
configService
.getHardwareConfiguration(new AsyncCallback<HardwareDto>() {
@Override
public void onSuccess(final HardwareDto result) {
int pres = 0, win = 0;
for (PresetDto preset : result.getPresets()) {
namePreset = namePreset + pres;
final Label $namePreset = new Label();
$namePreset.setTop((pres * 164) + 2);
$namePreset.setLeft(7);
$namePreset.setWidth(164);
$namePreset.setHeight(62);
$namePreset.setShowEdges(true);
$namePreset.setBorder("2px solid black");
$namePreset.setMaxWidth(164);
$namePreset.setMaxHeight(62);
$namePreset.setBackgroundColor("lightgrey");
$namePreset.setProperty("preset", pres);
$namePreset.draw();
// $namePreset
// .addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(
// DoubleClickEvent event) {
// event.getSource();
// bus.fireEvent(new AnimateEvent(0));
// for (int count = 0; count <= result
// .getPresets().size(); count++) {
// $namePreset.animateFade(30,
// null, 1000);
//// $namePreset.animateFade(100,
//// null, 1000);
// }
// }
// });
pres++;
for (WindowDto window : preset.getWindows()) {
windowN = windowN + win;
final Label $windowN = new Label();
$windowN.setTop(window.getYTopLeft() / 20);
$windowN.setLeft(window.getXTopLeft() / 10);
$windowN.setWidth((window.getXBottomRight() - window
.getXTopLeft()) / 10);
$windowN.setHeight((window.getYBottomRight() - window
.getYTopLeft()) / 20);
$windowN.setBorder("1px solid black");
$windowN.setBackgroundColor("darkgrey");
$windowN.draw();
$namePreset.addChild($windowN);
win++;
}
;
sectionStack.addChild($namePreset);
}
}
@Override
public void onFailure(Throwable caught) {
SC.say("Configurations are not available!");
caught.printStackTrace();
}
});
// drawPane2.addDoubleClickHandler(new DoubleClickHandler() {
// @Override
// public void onDoubleClick(DoubleClickEvent event) {
// drawPane2.animateFade(30, null, 1000);
// bus.fireEvent(new AnimateEvent(1));
// drawPane.animateFade(100, null, 1000);
// }
// });
//
// DrawLabel name1 = new DrawLabel();
// name1.setDrawPane(drawPane);
// name1.setLeft(33);
// name1.setTop(24);
// name1.setContents("One to All");
// name1.setLineWidth(1);
// name1.setFontSize(11);
// name1.draw();
// sectionStack.addSection(section1);
this.addMember(sectionStack);
}
|
diff --git a/src/main/java/tconstruct/armor/ArmorProxyClient.java b/src/main/java/tconstruct/armor/ArmorProxyClient.java
index 2461b5052..c9288d712 100644
--- a/src/main/java/tconstruct/armor/ArmorProxyClient.java
+++ b/src/main/java/tconstruct/armor/ArmorProxyClient.java
@@ -1,503 +1,505 @@
package tconstruct.armor;
import com.google.common.collect.Lists;
import cpw.mods.fml.common.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import java.util.*;
import mantle.lib.client.MantleClientRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.settings.*;
import net.minecraft.entity.*;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.*;
import net.minecraft.item.*;
import net.minecraft.potion.*;
import net.minecraft.util.*;
import net.minecraft.world.World;
import net.minecraftforge.client.GuiIngameForge;
import net.minecraftforge.client.event.*;
import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType;
import net.minecraftforge.common.MinecraftForge;
import tconstruct.armor.gui.*;
import tconstruct.armor.items.TravelGear;
import tconstruct.armor.model.*;
import tconstruct.armor.player.*;
import tconstruct.client.*;
import tconstruct.client.tabs.*;
import tconstruct.common.TProxyCommon;
import tconstruct.library.accessory.IAccessoryModel;
import tconstruct.library.client.TConstructClientRegistry;
import tconstruct.library.crafting.ModifyBuilder;
import tconstruct.tools.TinkerTools;
import tconstruct.world.TinkerWorld;
public class ArmorProxyClient extends ArmorProxyCommon
{
public static WingModel wings = new WingModel();
public static BootBump bootbump = new BootBump();
public static HiddenPlayerModel glove = new HiddenPlayerModel(0.25F, 4);
public static HiddenPlayerModel vest = new HiddenPlayerModel(0.25f, 1);
public static BeltModel belt = new BeltModel();
public static KnapsackInventory knapsack = new KnapsackInventory();
public static ArmorExtended armorExtended = new ArmorExtended();
@Override
public void initialize ()
{
registerGuiHandler();
registerKeys();
registerManualIcons();
registerManualRecipes();
MinecraftForge.EVENT_BUS.register(this);
FMLCommonHandler.instance().bus().register(new ArmorAbilitiesClient(mc, controlInstance));
}
private void registerManualIcons ()
{
MantleClientRegistry.registerManualIcon("travelgoggles", TinkerArmor.travelGoggles.getDefaultItem());
MantleClientRegistry.registerManualIcon("travelvest", TinkerArmor.travelVest.getDefaultItem());
MantleClientRegistry.registerManualIcon("travelwings", TinkerArmor.travelWings.getDefaultItem());
MantleClientRegistry.registerManualIcon("travelboots", TinkerArmor.travelBoots.getDefaultItem());
MantleClientRegistry.registerManualIcon("travelbelt", TinkerArmor.travelBelt.getDefaultItem());
MantleClientRegistry.registerManualIcon("travelglove", TinkerArmor.travelGlove.getDefaultItem());
}
private void registerManualRecipes ()
{
ItemStack feather = new ItemStack(Items.feather);
ItemStack redstone = new ItemStack(Items.redstone);
ItemStack goggles = TinkerArmor.travelGoggles.getDefaultItem();
TConstructClientRegistry.registerManualModifier("nightvision", goggles.copy(), new ItemStack(Items.flint_and_steel), new ItemStack(Items.potionitem, 1, 8198), new ItemStack(Items.golden_carrot), null);
ItemStack vest = TinkerArmor.travelVest.getDefaultItem();
TConstructClientRegistry.registerManualModifier("dodge", vest.copy(), new ItemStack(Items.ender_eye), new ItemStack(Items.ender_pearl), new ItemStack(Items.sugar), null);
TConstructClientRegistry.registerManualModifier("stealth", vest.copy(), new ItemStack(Items.fermented_spider_eye), new ItemStack(Items.ender_eye), new ItemStack(Items.potionitem, 1, 8206), new ItemStack(Items.golden_carrot));
ItemStack wings = TinkerArmor.travelWings.getDefaultItem();
TConstructClientRegistry.registerManualModifier("doublejumpwings", wings.copy(), new ItemStack(Items.ghast_tear), new ItemStack(TinkerWorld.slimeGel, 1, 0), new ItemStack(Blocks.piston), null);
ItemStack[] recipe = new ItemStack[] { new ItemStack(TinkerWorld.slimeGel, 1, 0), new ItemStack(Items.ender_pearl), feather, feather, feather, feather, feather, feather };
ItemStack modWings = ModifyBuilder.instance.modifyItem(wings, recipe);
MantleClientRegistry.registerManualLargeRecipe("featherfall", modWings.copy(), feather, new ItemStack(TinkerWorld.slimeGel, 1, 0), feather, feather, wings.copy(), feather, feather, new ItemStack(Items.ender_pearl), feather);
ItemStack boots = TinkerArmor.travelBoots.getDefaultItem();
TConstructClientRegistry.registerManualModifier("doublejumpboots", boots.copy(), new ItemStack(Items.ghast_tear), new ItemStack(TinkerWorld.slimeGel, 1, 1), new ItemStack(Blocks.piston), null);
TConstructClientRegistry.registerManualModifier("waterwalk", boots.copy(), new ItemStack(Blocks.waterlily), new ItemStack(Blocks.waterlily));
TConstructClientRegistry.registerManualModifier("leadboots", boots.copy(), new ItemStack(Blocks.iron_block));
TConstructClientRegistry.registerManualModifier("slimysoles", boots.copy(), new ItemStack(TinkerWorld.slimePad, 1, 0), new ItemStack(TinkerWorld.slimePad, 1, 0));
ItemStack gloves = TinkerArmor.travelGlove.getDefaultItem();
TConstructClientRegistry.registerManualModifier("glovehaste", gloves.copy(), redstone, new ItemStack(Blocks.redstone_block));
//MantleClientRegistry.registerManualSmallRecipe("gloveclimb", gloves.copy(), new ItemStack(Items.slime_ball), new ItemStack(Blocks.web), new ItemStack(TinkerTools.materials, 1, 25), null);
TConstructClientRegistry.registerManualModifier("gloveknuckles", gloves.copy(), new ItemStack(Items.quartz), new ItemStack(Blocks.quartz_block, 1, Short.MAX_VALUE));
// moss
ItemStack moss = new ItemStack(TinkerTools.materials, 1, 6);
TConstructClientRegistry.registerManualModifier("mossgoggles", goggles.copy(), moss.copy());
TConstructClientRegistry.registerManualModifier("mossvest", vest.copy(), moss.copy());
TConstructClientRegistry.registerManualModifier("mosswings", wings.copy(), moss.copy());
TConstructClientRegistry.registerManualModifier("mossboots", boots.copy(), moss.copy());
}
@Override
protected void registerGuiHandler ()
{
super.registerGuiHandler();
TProxyCommon.registerClientGuiHandler(inventoryGui, this);
TProxyCommon.registerClientGuiHandler(armorGuiID, this);
TProxyCommon.registerClientGuiHandler(knapsackGuiID, this);
}
@Override
public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z)
{
if (ID == ArmorProxyCommon.inventoryGui)
{
GuiInventory inventory = new GuiInventory(player);
return inventory;
}
if (ID == ArmorProxyCommon.armorGuiID)
{
ArmorProxyClient.armorExtended.init(Minecraft.getMinecraft().thePlayer);
return new ArmorExtendedGui(player.inventory, ArmorProxyClient.armorExtended);
}
if (ID == ArmorProxyCommon.knapsackGuiID)
{
ArmorProxyClient.knapsack.init(Minecraft.getMinecraft().thePlayer);
return new KnapsackGui(player.inventory, ArmorProxyClient.knapsack);
}
return null;
}
@Override
public void registerTickHandler ()
{
FMLCommonHandler.instance().bus().register(new ArmorTickHandler());
}
/* Keybindings */
public static ArmorControls controlInstance;
@Override
public void registerKeys ()
{
controlInstance = new ArmorControls();
uploadKeyBindingsToGame(Minecraft.getMinecraft().gameSettings, controlInstance);
TabRegistry.registerTab(new InventoryTabVanilla());
TabRegistry.registerTab(new InventoryTabArmorExtended());
TabRegistry.registerTab(new InventoryTabKnapsack());
}
public void uploadKeyBindingsToGame (GameSettings settings, TKeyHandler keyhandler)
{
ArrayList<KeyBinding> harvestedBindings = Lists.newArrayList();
for (KeyBinding kb : keyhandler.keyBindings)
{
harvestedBindings.add(kb);
}
KeyBinding[] modKeyBindings = harvestedBindings.toArray(new KeyBinding[harvestedBindings.size()]);
KeyBinding[] allKeys = new KeyBinding[settings.keyBindings.length + modKeyBindings.length];
System.arraycopy(settings.keyBindings, 0, allKeys, 0, settings.keyBindings.length);
System.arraycopy(modKeyBindings, 0, allKeys, settings.keyBindings.length, modKeyBindings.length);
settings.keyBindings = allKeys;
settings.loadOptions();
}
Minecraft mc = Minecraft.getMinecraft();
private static final ResourceLocation hearts = new ResourceLocation("tinker", "textures/gui/newhearts.png");
private static final ResourceLocation icons = new ResourceLocation("textures/gui/icons.png");
// public static int left_height = 39;
// public static int right_height = 39;
Random rand = new Random();
int updateCounter = 0;
GameSettings gs = Minecraft.getMinecraft().gameSettings;
@SubscribeEvent
public void goggleZoom (FOVUpdateEvent event)
{
if (ArmorControls.zoom)
{
ItemStack helmet = event.entity.getCurrentArmor(3);
if (helmet != null && helmet.getItem() instanceof TravelGear)
{
event.newfov = 0.3f;
}
}
//ItemStack feet = player.getCurrentArmor(0);
//event.newfov = 1.0f;
}
/* HUD */
@SubscribeEvent
public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
if(Loader.isModLoaded("rpghud")) // uses different display, displays health correctly by itself.
return;
if (!Loader.isModLoaded("tukmc_Vz") || Loader.isModLoaded("borderlands"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
if (!GuiIngameForge.renderExperiance)
{
top += 7;
yBasePos += 7;
}
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
int potionOffset = 0;
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
potionOffset = 18;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
potionOffset = 9;
+ if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled())
+ potionOffset += 27;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
int y = 0;
if (i == regen)
y -= 2;
this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * iter, potionOffset, 9, 9);
}
if (hp % 2 == 1 && renderHearts < 10)
{
this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, potionOffset, 9, 9);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
public void drawTexturedModalRect (int par1, int par2, int par3, int par4, int par5, int par6)
{
float f = 0.00390625F;
float f1 = 0.00390625F;
Tessellator tessellator = Tessellator.instance;
tessellator.startDrawingQuads();
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + par6), (double) this.zLevel, (double) ((float) (par3 + 0) * f), (double) ((float) (par4 + par6) * f1));
tessellator.addVertexWithUV((double) (par1 + par5), (double) (par2 + par6), (double) this.zLevel, (double) ((float) (par3 + par5) * f), (double) ((float) (par4 + par6) * f1));
tessellator.addVertexWithUV((double) (par1 + par5), (double) (par2 + 0), (double) this.zLevel, (double) ((float) (par3 + par5) * f), (double) ((float) (par4 + 0) * f1));
tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + 0), (double) this.zLevel, (double) ((float) (par3 + 0) * f), (double) ((float) (par4 + 0) * f1));
tessellator.draw();
}
double zLevel = 0;
/* Armor rendering */
@SubscribeEvent
public void adjustArmor (RenderPlayerEvent.SetArmorModel event)
{
switch (event.slot)
{
case 1:
ArmorProxyClient.vest.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.vest.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.vest.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.vest.isSneak = event.renderer.modelBipedMain.isSneak;
case 2:
ArmorProxyClient.wings.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.wings.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.wings.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.wings.isSneak = event.renderer.modelBipedMain.isSneak;
ArmorProxyClient.glove.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.glove.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.glove.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.glove.isSneak = event.renderer.modelBipedMain.isSneak;
ArmorProxyClient.glove.heldItemLeft = event.renderer.modelBipedMain.heldItemLeft;
ArmorProxyClient.glove.heldItemRight = event.renderer.modelBipedMain.heldItemRight;
ArmorProxyClient.belt.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.belt.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.belt.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.belt.isSneak = event.renderer.modelBipedMain.isSneak;
renderArmorExtras(event);
break;
case 3:
ArmorProxyClient.bootbump.onGround = event.renderer.modelBipedMain.onGround;
ArmorProxyClient.bootbump.isRiding = event.renderer.modelBipedMain.isRiding;
ArmorProxyClient.bootbump.isChild = event.renderer.modelBipedMain.isChild;
ArmorProxyClient.bootbump.isSneak = event.renderer.modelBipedMain.isSneak;
break;
}
}
void renderArmorExtras (RenderPlayerEvent.SetArmorModel event)
{
float partialTick = event.partialRenderTick;
EntityPlayer player = event.entityPlayer;
// todo: synchronize extra armor with other clients. Until then, only draw locally
if(player != Minecraft.getMinecraft().thePlayer)
return;
float posX = (float) (player.lastTickPosX + (player.posX - player.lastTickPosX) * partialTick);
float posY = (float) (player.lastTickPosY + (player.posY - player.lastTickPosY) * partialTick);
float posZ = (float) (player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * partialTick);
float yawOffset = this.interpolateRotation(player.prevRenderYawOffset, player.renderYawOffset, partialTick);
float yawRotation = this.interpolateRotation(player.prevRotationYawHead, player.rotationYawHead, partialTick);
float pitch;
final float zeropointsixtwofive = 0.0625F;
if (player.isRiding() && player.ridingEntity instanceof EntityLivingBase)
{
EntityLivingBase entitylivingbase1 = (EntityLivingBase) player.ridingEntity;
yawOffset = this.interpolateRotation(entitylivingbase1.prevRenderYawOffset, entitylivingbase1.renderYawOffset, partialTick);
pitch = MathHelper.wrapAngleTo180_float(yawRotation - yawOffset);
if (pitch < -85.0F)
{
pitch = -85.0F;
}
if (pitch >= 85.0F)
{
pitch = 85.0F;
}
yawOffset = yawRotation - pitch;
if (pitch * pitch > 2500.0F)
{
yawOffset += pitch * 0.2F;
}
}
pitch = this.handleRotationFloat(player, partialTick);
float bodyRotation = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * partialTick;
float limbSwing = player.prevLimbSwingAmount + (player.limbSwingAmount - player.prevLimbSwingAmount) * partialTick;
float limbSwingMod = player.limbSwing - player.limbSwingAmount * (1.0F - partialTick);
//TPlayerStats stats = TPlayerStats.get(player);
ArmorExtended armor = ArmorProxyClient.armorExtended; //TODO: Do this for every player, not just the client
if (armor.inventory[1] != null)
{
Item item = armor.inventory[1].getItem();
ModelBiped model = item.getArmorModel(player, armor.inventory[1], 4);
if (item instanceof IAccessoryModel)
{
this.mc.getTextureManager().bindTexture(((IAccessoryModel) item).getWearbleTexture(player, armor.inventory[1], 1));
model.setLivingAnimations(player, limbSwingMod, limbSwing, partialTick);
model.render(player, limbSwingMod, limbSwing, pitch, yawRotation - yawOffset, bodyRotation, zeropointsixtwofive);
}
}
if (armor.inventory[3] != null)
{
Item item = armor.inventory[3].getItem();
ModelBiped model = item.getArmorModel(player, armor.inventory[3], 5);
if (item instanceof IAccessoryModel)
{
this.mc.getTextureManager().bindTexture(((IAccessoryModel) item).getWearbleTexture(player, armor.inventory[1], 1));
model.setLivingAnimations(player, limbSwingMod, limbSwing, partialTick);
model.render(player, limbSwingMod, limbSwing, pitch, yawRotation - yawOffset, bodyRotation, zeropointsixtwofive);
}
}
}
private float interpolateRotation (float par1, float par2, float par3)
{
float f3;
for (f3 = par2 - par1; f3 < -180.0F; f3 += 360.0F)
{
;
}
while (f3 >= 180.0F)
{
f3 -= 360.0F;
}
return par1 + par3 * f3;
}
protected float handleRotationFloat (EntityLivingBase par1EntityLivingBase, float par2)
{
return (float) par1EntityLivingBase.ticksExisted + par2;
}
}
| true | true | public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
if(Loader.isModLoaded("rpghud")) // uses different display, displays health correctly by itself.
return;
if (!Loader.isModLoaded("tukmc_Vz") || Loader.isModLoaded("borderlands"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
if (!GuiIngameForge.renderExperiance)
{
top += 7;
yBasePos += 7;
}
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
int potionOffset = 0;
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
potionOffset = 18;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
potionOffset = 9;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
int y = 0;
if (i == regen)
y -= 2;
this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * iter, potionOffset, 9, 9);
}
if (hp % 2 == 1 && renderHearts < 10)
{
this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, potionOffset, 9, 9);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
| public void renderHealthbar (RenderGameOverlayEvent.Pre event)
{
if(Loader.isModLoaded("rpghud")) // uses different display, displays health correctly by itself.
return;
if (!Loader.isModLoaded("tukmc_Vz") || Loader.isModLoaded("borderlands"))// Loader check to avoid conflicting
// with a GUI mod (thanks Vazkii!)
{
if (event.type == ElementType.HEALTH)
{
updateCounter++;
ScaledResolution scaledresolution = new ScaledResolution(this.mc, this.mc.displayWidth, this.mc.displayHeight);
int scaledWidth = scaledresolution.getScaledWidth();
int scaledHeight = scaledresolution.getScaledHeight();
int xBasePos = scaledWidth / 2 - 91;
int yBasePos = scaledHeight - 39;
boolean highlight = mc.thePlayer.hurtResistantTime / 3 % 2 == 1;
if (mc.thePlayer.hurtResistantTime < 10)
{
highlight = false;
}
IAttributeInstance attrMaxHealth = this.mc.thePlayer.getEntityAttribute(SharedMonsterAttributes.maxHealth);
int health = MathHelper.ceiling_float_int(mc.thePlayer.getHealth());
int healthLast = MathHelper.ceiling_float_int(mc.thePlayer.prevHealth);
float healthMax = (float) attrMaxHealth.getAttributeValue();
if (healthMax > 20)
healthMax = 20;
float absorb = this.mc.thePlayer.getAbsorptionAmount();
int healthRows = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F / 10.0F);
int rowHeight = Math.max(10 - (healthRows - 2), 3);
this.rand.setSeed((long) (updateCounter * 312871));
int left = scaledWidth / 2 - 91;
int top = scaledHeight - GuiIngameForge.left_height;
if (!GuiIngameForge.renderExperiance)
{
top += 7;
yBasePos += 7;
}
int regen = -1;
if (mc.thePlayer.isPotionActive(Potion.regeneration))
{
regen = updateCounter % 25;
}
final int TOP = 9 * (mc.theWorld.getWorldInfo().isHardcoreModeEnabled() ? 5 : 0);
final int BACKGROUND = (highlight ? 25 : 16);
int MARGIN = 16;
if (mc.thePlayer.isPotionActive(Potion.poison))
MARGIN += 36;
else if (mc.thePlayer.isPotionActive(Potion.wither))
MARGIN += 72;
float absorbRemaining = absorb;
for (int i = MathHelper.ceiling_float_int((healthMax + absorb) / 2.0F) - 1; i >= 0; --i)
{
int b0 = (highlight ? 1 : 0);
int row = MathHelper.ceiling_float_int((float) (i + 1) / 10.0F) - 1;
int x = left + i % 10 * 8;
int y = top - row * rowHeight;
if (health <= 4)
y += rand.nextInt(2);
if (i == regen)
y -= 2;
drawTexturedModalRect(x, y, BACKGROUND, TOP, 9, 9);
if (highlight)
{
if (i * 2 + 1 < healthLast)
drawTexturedModalRect(x, y, MARGIN + 54, TOP, 9, 9); // 6
else if (i * 2 + 1 == healthLast)
drawTexturedModalRect(x, y, MARGIN + 63, TOP, 9, 9); // 7
}
if (absorbRemaining > 0.0F)
{
if (absorbRemaining == absorb && absorb % 2.0F == 1.0F)
drawTexturedModalRect(x, y, MARGIN + 153, TOP, 9, 9); // 17
else
drawTexturedModalRect(x, y, MARGIN + 144, TOP, 9, 9); // 16
absorbRemaining -= 2.0F;
}
else
{
if (i * 2 + 1 < health)
drawTexturedModalRect(x, y, MARGIN + 36, TOP, 9, 9); // 4
else if (i * 2 + 1 == health)
drawTexturedModalRect(x, y, MARGIN + 45, TOP, 9, 9); // 5
}
}
int potionOffset = 0;
PotionEffect potion = mc.thePlayer.getActivePotionEffect(Potion.wither);
if (potion != null)
potionOffset = 18;
potion = mc.thePlayer.getActivePotionEffect(Potion.poison);
if (potion != null)
potionOffset = 9;
if (mc.theWorld.getWorldInfo().isHardcoreModeEnabled())
potionOffset += 27;
// Extra hearts
this.mc.getTextureManager().bindTexture(hearts);
int hp = MathHelper.ceiling_float_int(this.mc.thePlayer.getHealth());
for (int iter = 0; iter < hp / 20; iter++)
{
int renderHearts = (hp - 20 * (iter + 1)) / 2;
if (renderHearts > 10)
renderHearts = 10;
for (int i = 0; i < renderHearts; i++)
{
int y = 0;
if (i == regen)
y -= 2;
this.drawTexturedModalRect(xBasePos + 8 * i, yBasePos + y, 0 + 18 * iter, potionOffset, 9, 9);
}
if (hp % 2 == 1 && renderHearts < 10)
{
this.drawTexturedModalRect(xBasePos + 8 * renderHearts, yBasePos, 9 + 18 * iter, potionOffset, 9, 9);
}
}
this.mc.getTextureManager().bindTexture(icons);
GuiIngameForge.left_height += 10;
if (absorb > 0)
GuiIngameForge.left_height += 10;
event.setCanceled(true);
if (event.type == ElementType.CROSSHAIRS && gs.thirdPersonView != 0)
{
event.setCanceled(true);
}
}
}
}
|
diff --git a/src/de/ub0r/android/smsdroid/MessageList.java b/src/de/ub0r/android/smsdroid/MessageList.java
index a6a0977..5592c64 100644
--- a/src/de/ub0r/android/smsdroid/MessageList.java
+++ b/src/de/ub0r/android/smsdroid/MessageList.java
@@ -1,550 +1,551 @@
/*
* Copyright (C) 2010 Felix Bechstein
*
* This file is part of SMSdroid.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; If not, see <http://www.gnu.org/licenses/>.
*/
package de.ub0r.android.smsdroid;
import android.app.ListActivity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.CallLog.Calls;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import de.ub0r.android.lib.Log;
import de.ub0r.android.lib.Utils;
import de.ub0r.android.lib.apis.ContactsWrapper;
import de.ub0r.android.lib.apis.TelephonyWrapper;
/**
* {@link ListActivity} showing a single conversation.
*
* @author flx
*/
public class MessageList extends ListActivity implements OnItemClickListener,
OnItemLongClickListener, OnClickListener, OnLongClickListener {
/** Tag for output. */
private static final String TAG = "ml";
/** {@link TelephonyWrapper}. */
public static final TelephonyWrapper TWRAPPER = TelephonyWrapper
.getInstance();
/** {@link ContactsWrapper}. */
private static final ContactsWrapper WRAPPER = ContactsWrapper
.getInstance();
/** Number of items. */
private static final int WHICH_N = 5;
// private static final int WHICH_N = 6;
/** Index in dialog: mark read/unread. */
private static final int WHICH_MARK_UNREAD = 0;
/** Index in dialog: forward. */
private static final int WHICH_FORWARD = 1;
/** Index in dialog: copy text. */
private static final int WHICH_COPY_TEXT = 2;
/** Index in dialog: view details. */
private static final int WHICH_VIEW_DETAILS = 3;
/** Index in dialog: delete. */
private static final int WHICH_DELETE = 4;
/** Index in dialog: speak. */
private static final int WHICH_SPEAK = 5;
/** Minimum length for showing sms length. */
private final int TEXT_LABLE_MIN_LEN = 50;
/** Used {@link Uri}. */
private Uri uri;
/** {@link Conversation} shown. */
private Conversation conv = null;
/** ORIG_URI to resolve. */
static final String URI = "content://mms-sms/conversations/";
/** Dialog items shown if an item was long clicked. */
private String[] longItemClickDialog = null;
/** Sort list upside down. */
private boolean sortUSD = true;
/** Current FooterView. */
private View currentHeader = null;
/** Marked a message unread? */
private boolean markedUnread = false;
/** {@link EditText} holding text. */
private EditText etText;
/** {@link TextView} for pasting text. */
private TextView tvPaste;
/** Text's label. */
private TextView etTextLabel;
/** {@link ClipboardManager}. */
private ClipboardManager cbmgr;
/** TextWatcher updating char count on writing. */
private TextWatcher textWatcher = new TextWatcher() {
/**
* {@inheritDoc}
*/
public void afterTextChanged(final Editable s) {
final int len = s.length();
if (len == 0) {
if (MessageList.this.cbmgr.hasText()) {
MessageList.this.tvPaste.setVisibility(View.VISIBLE);
} else {
MessageList.this.tvPaste.setVisibility(View.GONE);
}
MessageList.this.etTextLabel.setVisibility(View.GONE);
} else {
MessageList.this.tvPaste.setVisibility(View.GONE);
if (len > MessageList.this.TEXT_LABLE_MIN_LEN) {
MessageList.this.etTextLabel.setVisibility(View.VISIBLE);
int[] l = TWRAPPER.calculateLength(s.toString(), false);
MessageList.this.etTextLabel.setText(l[0] + "/" + l[2]);
} else {
MessageList.this.etTextLabel.setVisibility(View.GONE);
}
}
}
/** Needed dummy. */
public void beforeTextChanged(final CharSequence s, final int start,
final int count, final int after) {
}
/** Needed dummy. */
public void onTextChanged(final CharSequence s, final int start,
final int before, final int count) {
}
};
/**
* {@inheritDoc}
*/
@Override
public final void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final boolean showTitlebar = prefs.getBoolean(
Preferences.PREFS_SHOWTITLEBAR, true);
this.setTheme(Preferences.getTheme(this));
Utils.setLocale(this);
this.setContentView(R.layout.messagelist);
if (!showTitlebar) {
this.findViewById(R.id.titlebar).setVisibility(View.GONE);
}
Log.d(TAG, "onCreate()");
this.cbmgr = (ClipboardManager) this
.getSystemService(CLIPBOARD_SERVICE);
this.etText = (EditText) this.findViewById(R.id.text);
this.etTextLabel = (TextView) this.findViewById(R.id.text_);
this.tvPaste = (TextView) this.findViewById(R.id.text_paste);
this.parseIntent(this.getIntent());
final ListView list = this.getListView();
list.setOnItemLongClickListener(this);
list.setOnItemClickListener(this);
View v = this.findViewById(R.id.send_);
v.setOnClickListener(this);
v.setOnLongClickListener(this);
this.tvPaste.setOnClickListener(this);
this.etText.addTextChangedListener(this.textWatcher);
this.textWatcher.afterTextChanged(this.etText.getEditableText());
this.longItemClickDialog = new String[WHICH_N];
this.longItemClickDialog[WHICH_MARK_UNREAD] = this
.getString(R.string.mark_unread_);
this.longItemClickDialog[WHICH_FORWARD] = this
.getString(R.string.forward_);
this.longItemClickDialog[WHICH_COPY_TEXT] = this
.getString(R.string.copy_text_);
this.longItemClickDialog[WHICH_VIEW_DETAILS] = this
.getString(R.string.view_details_);
this.longItemClickDialog[WHICH_DELETE] = this
.getString(R.string.delete_message_);
// this.longItemClickDialog[WHICH_SPEAK] =
// this.getString(R.string.speak_);
}
/**
* {@inheritDoc}
*/
@Override
protected final void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
this.parseIntent(intent);
}
/**
* Parse data pushed by {@link Intent}.
*
* @param intent
* {@link Intent}
*/
private void parseIntent(final Intent intent) {
Log.d(TAG, "parseIntent(" + intent + ")");
if (intent == null) {
return;
}
Log.d(TAG, "got action: " + intent.getAction());
Log.d(TAG, "got uri: " + intent.getData());
this.uri = intent.getData();
if (this.uri != null) {
if (!this.uri.toString().startsWith(URI)) {
this.uri = Uri.parse(URI + this.uri.getLastPathSegment());
}
} else {
final long tid = intent.getLongExtra("thread_id", -1L);
this.uri = Uri.parse(URI + tid);
if (tid < 0L) {
this.startActivity(ConversationList.getComposeIntent(null));
this.finish();
return;
}
}
final int threadId = Integer.parseInt(this.uri.getLastPathSegment());
final Conversation c = Conversation.getConversation(this, threadId,
true);
this.conv = c;
if (c == null) {
Toast.makeText(this, R.string.error_conv_null, Toast.LENGTH_LONG)
.show();
this.finish();
return;
}
Log.d(TAG, "address: " + c.getAddress());
Log.d(TAG, "name: " + c.getName());
Log.d(TAG, "displayName: " + c.getDisplayName());
final ListView lv = this.getListView();
lv.setStackFromBottom(true);
MessageAdapter adapter = new MessageAdapter(this, this.uri);
this.setListAdapter(adapter);
String str;
final String name = c.getName();
if (name == null) {
str = c.getAddress();
} else {
final ImageView ivPhoto = (ImageView) this.findViewById(R.id.photo);
Bitmap b = c.getPhoto();
if (b != null && b != Conversation.NO_PHOTO) {
ivPhoto.setImageBitmap(b);
} else {
ivPhoto.setImageResource(R.drawable.ic_contact_picture);
}
ivPhoto.setOnClickListener(WRAPPER.getQuickContact(this, ivPhoto, c
.getAddress(), 2, null));
ivPhoto.setVisibility(View.VISIBLE);
str = name + " <" + c.getAddress() + ">";
}
((TextView) this.findViewById(R.id.contact)).setText(str);
this.setRead();
}
/**
* Set selection to "answer" button.
*/
private void scrollToLastMessage() {
final ListView lv = this.getListView();
lv.setAdapter(new MessageAdapter(this, this.uri));
lv.setSelection(this.getListAdapter().getCount() - 1);
this.etText.requestFocus();
}
/**
* {@inheritDoc}
*/
@Override
public final void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.scrollToLastMessage();
}
/**
* {@inheritDoc}
*/
@Override
protected final void onResume() {
super.onResume();
this.markedUnread = false;
this.scrollToLastMessage();
}
/**
* {@inheritDoc}
*/
@Override
protected final void onPause() {
super.onPause();
if (!this.markedUnread) {
this.setRead();
}
}
/**
* Set all messages in a given thread as read.
*/
private void setRead() {
if (this.conv != null) {
ConversationList.markRead(this, this.conv.getUri(), 1);
}
}
/**
* {@inheritDoc}
*/
@Override
public final boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = this.getMenuInflater();
inflater.inflate(R.menu.messagelist, menu);
return true;
}
/**
*{@inheritDoc}
*/
@Override
public final boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.item_delete_thread:
ConversationList.deleteMessages(this, this.uri,
R.string.delete_thread_, R.string.delete_thread_question,
this);
return true;
case R.id.item_all_threads:
this.startActivity(new Intent(this, ConversationList.class));
return true;
case R.id.item_compose:
this.startActivity(ConversationList.getComposeIntent(null));
return true;
case R.id.item_answer:
this.startActivity(ConversationList.getComposeIntent(this.conv
.getAddress()));
return true;
case R.id.item_call:
this.startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
+ this.conv.getAddress())));
return true;
default:
return false;
}
}
/**
* {@inheritDoc}
*/
public final void onItemClick(final AdapterView<?> parent, final View view,
final int position, final long id) {
this.onItemLongClick(parent, view, position, id);
}
/**
* {@inheritDoc}
*/
public final boolean onItemLongClick(final AdapterView<?> parent,
final View view, final int position, final long id) {
final Context context = this;
final Message m = Message.getMessage(this, (Cursor) parent
.getItemAtPosition(position));
final Uri target = m.getUri();
final int read = m.getRead();
final int type = m.getType();
Builder builder = new Builder(context);
builder.setTitle(R.string.message_options_);
String[] items = this.longItemClickDialog;
if (read == 0) {
items = items.clone();
items[WHICH_MARK_UNREAD] = context.getString(R.string.mark_read_);
}
if (type == Message.SMS_DRAFT) {
items = items.clone();
items[WHICH_FORWARD] = context.getString(R.string.send_draft_);
}
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
switch (which) {
case WHICH_MARK_UNREAD:
ConversationList.markRead(context, target, 1 - read);
MessageList.this.markedUnread = true;
break;
case WHICH_FORWARD:
Intent i;
int resId;
if (type == Message.SMS_DRAFT) {
resId = R.string.send_draft_;
i = ConversationList
.getComposeIntent(MessageList.this.conv
.getAddress());
} else {
resId = R.string.forward_;
i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
+ i.putExtra("forwarded_message", true);
}
final CharSequence text = m.getBody();
i.putExtra(Intent.EXTRA_TEXT, text);
i.putExtra("sms_body", text);
context.startActivity(Intent.createChooser(i, context
.getString(resId)));
break;
case WHICH_COPY_TEXT:
final ClipboardManager cm = // .
(ClipboardManager) context.getSystemService(// .
Context.CLIPBOARD_SERVICE);
cm.setText(m.getBody());
break;
case WHICH_VIEW_DETAILS:
final int t = m.getType();
Builder b = new Builder(context);
b.setTitle(R.string.view_details_);
b.setCancelable(true);
StringBuilder sb = new StringBuilder();
final String a = m.getAddress(context);
final long d = m.getDate();
final String ds = DateFormat.format(// .
context.getString(// .
R.string.DATEFORMAT_details), d).toString();
String sentReceived;
String fromTo;
if (t == Calls.INCOMING_TYPE) {
sentReceived = context.getString(R.string.received_);
fromTo = context.getString(R.string.from_);
} else if (t == Calls.OUTGOING_TYPE) {
sentReceived = context.getString(R.string.sent_);
fromTo = context.getString(R.string.to_);
} else {
sentReceived = "ukwn:";
fromTo = "ukwn:";
}
sb.append(sentReceived + " ");
sb.append(ds);
sb.append("\n");
sb.append(fromTo + " ");
sb.append(a);
sb.append("\n");
sb.append(context.getString(R.string.type_));
if (m.isMMS()) {
sb.append(" MMS");
} else {
sb.append(" SMS");
}
b.setMessage(sb.toString());
b.setPositiveButton(android.R.string.ok, null);
b.show();
break;
case WHICH_DELETE:
ConversationList.deleteMessages(context, target,
R.string.delete_message_,
R.string.delete_message_question, null);
break;
case WHICH_SPEAK:
// TODO: implement me
Toast.makeText(context, R.string.not_implemented,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
builder.show();
return true;
}
/**
* {@inheritDoc}
*/
public final void onClick(final View v) {
switch (v.getId()) {
case R.id.send_:
final String text = this.etText.getText().toString().trim();
if (text.length() == 0) {
return;
}
final Intent i = ConversationList.getComposeIntent(this.conv
.getAddress());
i.putExtra(Intent.EXTRA_TEXT, text);
i.putExtra("sms_body", text);
i.putExtra("AUTOSEND", "1");
this.startActivity(i);
this.etText.setText("");
return;
case R.id.text_paste:
final CharSequence s = this.cbmgr.getText();
this.etText.setText(s);
return;
default:
return;
}
}
/**
* {@inheritDoc}
*/
public final boolean onLongClick(final View v) {
switch (v.getId()) {
case R.id.send_:
final String text = this.etText.getText().toString().trim();
if (text.length() == 0) {
return true;
}
final Intent i = ConversationList.getComposeIntent(this.conv
.getAddress());
i.putExtra(Intent.EXTRA_TEXT, text);
i.putExtra("sms_body", text);
this.startActivity(Intent.createChooser(i, this
.getString(R.string.answer)));
this.etText.setText("");
return true;
default:
return true;
}
}
}
| true | true | public final boolean onItemLongClick(final AdapterView<?> parent,
final View view, final int position, final long id) {
final Context context = this;
final Message m = Message.getMessage(this, (Cursor) parent
.getItemAtPosition(position));
final Uri target = m.getUri();
final int read = m.getRead();
final int type = m.getType();
Builder builder = new Builder(context);
builder.setTitle(R.string.message_options_);
String[] items = this.longItemClickDialog;
if (read == 0) {
items = items.clone();
items[WHICH_MARK_UNREAD] = context.getString(R.string.mark_read_);
}
if (type == Message.SMS_DRAFT) {
items = items.clone();
items[WHICH_FORWARD] = context.getString(R.string.send_draft_);
}
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
switch (which) {
case WHICH_MARK_UNREAD:
ConversationList.markRead(context, target, 1 - read);
MessageList.this.markedUnread = true;
break;
case WHICH_FORWARD:
Intent i;
int resId;
if (type == Message.SMS_DRAFT) {
resId = R.string.send_draft_;
i = ConversationList
.getComposeIntent(MessageList.this.conv
.getAddress());
} else {
resId = R.string.forward_;
i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
}
final CharSequence text = m.getBody();
i.putExtra(Intent.EXTRA_TEXT, text);
i.putExtra("sms_body", text);
context.startActivity(Intent.createChooser(i, context
.getString(resId)));
break;
case WHICH_COPY_TEXT:
final ClipboardManager cm = // .
(ClipboardManager) context.getSystemService(// .
Context.CLIPBOARD_SERVICE);
cm.setText(m.getBody());
break;
case WHICH_VIEW_DETAILS:
final int t = m.getType();
Builder b = new Builder(context);
b.setTitle(R.string.view_details_);
b.setCancelable(true);
StringBuilder sb = new StringBuilder();
final String a = m.getAddress(context);
final long d = m.getDate();
final String ds = DateFormat.format(// .
context.getString(// .
R.string.DATEFORMAT_details), d).toString();
String sentReceived;
String fromTo;
if (t == Calls.INCOMING_TYPE) {
sentReceived = context.getString(R.string.received_);
fromTo = context.getString(R.string.from_);
} else if (t == Calls.OUTGOING_TYPE) {
sentReceived = context.getString(R.string.sent_);
fromTo = context.getString(R.string.to_);
} else {
sentReceived = "ukwn:";
fromTo = "ukwn:";
}
sb.append(sentReceived + " ");
sb.append(ds);
sb.append("\n");
sb.append(fromTo + " ");
sb.append(a);
sb.append("\n");
sb.append(context.getString(R.string.type_));
if (m.isMMS()) {
sb.append(" MMS");
} else {
sb.append(" SMS");
}
b.setMessage(sb.toString());
b.setPositiveButton(android.R.string.ok, null);
b.show();
break;
case WHICH_DELETE:
ConversationList.deleteMessages(context, target,
R.string.delete_message_,
R.string.delete_message_question, null);
break;
case WHICH_SPEAK:
// TODO: implement me
Toast.makeText(context, R.string.not_implemented,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
builder.show();
return true;
}
| public final boolean onItemLongClick(final AdapterView<?> parent,
final View view, final int position, final long id) {
final Context context = this;
final Message m = Message.getMessage(this, (Cursor) parent
.getItemAtPosition(position));
final Uri target = m.getUri();
final int read = m.getRead();
final int type = m.getType();
Builder builder = new Builder(context);
builder.setTitle(R.string.message_options_);
String[] items = this.longItemClickDialog;
if (read == 0) {
items = items.clone();
items[WHICH_MARK_UNREAD] = context.getString(R.string.mark_read_);
}
if (type == Message.SMS_DRAFT) {
items = items.clone();
items[WHICH_FORWARD] = context.getString(R.string.send_draft_);
}
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
switch (which) {
case WHICH_MARK_UNREAD:
ConversationList.markRead(context, target, 1 - read);
MessageList.this.markedUnread = true;
break;
case WHICH_FORWARD:
Intent i;
int resId;
if (type == Message.SMS_DRAFT) {
resId = R.string.send_draft_;
i = ConversationList
.getComposeIntent(MessageList.this.conv
.getAddress());
} else {
resId = R.string.forward_;
i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra("forwarded_message", true);
}
final CharSequence text = m.getBody();
i.putExtra(Intent.EXTRA_TEXT, text);
i.putExtra("sms_body", text);
context.startActivity(Intent.createChooser(i, context
.getString(resId)));
break;
case WHICH_COPY_TEXT:
final ClipboardManager cm = // .
(ClipboardManager) context.getSystemService(// .
Context.CLIPBOARD_SERVICE);
cm.setText(m.getBody());
break;
case WHICH_VIEW_DETAILS:
final int t = m.getType();
Builder b = new Builder(context);
b.setTitle(R.string.view_details_);
b.setCancelable(true);
StringBuilder sb = new StringBuilder();
final String a = m.getAddress(context);
final long d = m.getDate();
final String ds = DateFormat.format(// .
context.getString(// .
R.string.DATEFORMAT_details), d).toString();
String sentReceived;
String fromTo;
if (t == Calls.INCOMING_TYPE) {
sentReceived = context.getString(R.string.received_);
fromTo = context.getString(R.string.from_);
} else if (t == Calls.OUTGOING_TYPE) {
sentReceived = context.getString(R.string.sent_);
fromTo = context.getString(R.string.to_);
} else {
sentReceived = "ukwn:";
fromTo = "ukwn:";
}
sb.append(sentReceived + " ");
sb.append(ds);
sb.append("\n");
sb.append(fromTo + " ");
sb.append(a);
sb.append("\n");
sb.append(context.getString(R.string.type_));
if (m.isMMS()) {
sb.append(" MMS");
} else {
sb.append(" SMS");
}
b.setMessage(sb.toString());
b.setPositiveButton(android.R.string.ok, null);
b.show();
break;
case WHICH_DELETE:
ConversationList.deleteMessages(context, target,
R.string.delete_message_,
R.string.delete_message_question, null);
break;
case WHICH_SPEAK:
// TODO: implement me
Toast.makeText(context, R.string.not_implemented,
Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
builder.show();
return true;
}
|
diff --git a/modules/cpr/src/test/java/org/atmosphere/cpr/ManagedAtmosphereHandlerTest.java b/modules/cpr/src/test/java/org/atmosphere/cpr/ManagedAtmosphereHandlerTest.java
index b10038dcf..f549482b3 100644
--- a/modules/cpr/src/test/java/org/atmosphere/cpr/ManagedAtmosphereHandlerTest.java
+++ b/modules/cpr/src/test/java/org/atmosphere/cpr/ManagedAtmosphereHandlerTest.java
@@ -1,203 +1,203 @@
/*
* Copyright 2012 Jean-Francois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.cpr;
import org.atmosphere.config.service.Delete;
import org.atmosphere.config.service.Get;
import org.atmosphere.config.service.ManagedAtmosphereHandlerService;
import org.atmosphere.config.service.Message;
import org.atmosphere.config.service.Post;
import org.atmosphere.config.service.Put;
import org.atmosphere.util.SimpleBroadcaster;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicReference;
import static org.mockito.Mockito.mock;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class ManagedAtmosphereHandlerTest {
private AtmosphereFramework framework;
private static final AtomicReference<AtmosphereResource> r = new AtomicReference<AtmosphereResource>();
private static final AtomicReference<String> message = new AtomicReference<String>();
@BeforeMethod
public void create() throws Throwable {
framework = new AtmosphereFramework();
framework.setDefaultBroadcasterClassName(SimpleBroadcaster.class.getName()) ;
String name = new File(".").getAbsolutePath();
- framework.setLibPath(name.substring(0, name.length() - 1) + "/modules/cpr/target/");
+ framework.setLibPath(name.substring(0, name.length() - 1) + "/target/");
framework.setAsyncSupport(new AsynchronousProcessor(framework.getAtmosphereConfig()) {
@Override
public Action service(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
return suspended(req, res);
}
public void action(AtmosphereResourceImpl r) {
try {
resumed(r.getRequest(), r.getResponse());
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}).init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
});
}
@AfterMethod
public void after() {
r.set(null);
framework.destroy();
}
@ManagedAtmosphereHandlerService(path = "/a")
public final static class ManagedGet {
@Get
public void get(AtmosphereResource resource) {
resource.suspend();
r.set(resource);
}
}
@Test
public void testGet() throws IOException, ServletException {
AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/a").method("GET").build();
framework.doCometSupport(request, AtmosphereResponse.newInstance());
r.get().resume();
assertNotNull(r.get());
}
@ManagedAtmosphereHandlerService(path = "/b")
public final static class ManagedPost {
@Post
public void post(AtmosphereResource resource) {
resource.suspend();
r.set(resource);
}
}
@Test
public void testPost() throws IOException, ServletException {
AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/b").method("POST").build();
framework.doCometSupport(request, AtmosphereResponse.newInstance());
assertNotNull(r.get());
r.get().resume();
}
@ManagedAtmosphereHandlerService(path = "/c")
public final static class ManagedDelete {
@Delete
public void delete(AtmosphereResource resource) {
resource.suspend();
r.set(resource);
}
}
@Test
public void testDelete() throws IOException, ServletException {
AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/c").method("DELETE").build();
framework.doCometSupport(request, AtmosphereResponse.newInstance());
assertNotNull(r.get());
r.get().resume();
}
@ManagedAtmosphereHandlerService(path = "/d")
public final static class ManagedPut {
@Put
public void put(AtmosphereResource resource) {
resource.suspend();
r.set(resource);
}
}
@Test
public void testPut() throws IOException, ServletException {
AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/d").method("PUT").build();
framework.doCometSupport(request, AtmosphereResponse.newInstance());
assertNotNull(r.get());
r.get().resume();
}
@ManagedAtmosphereHandlerService(path = "/e")
public final static class ManagedMessage {
@Get
public void get(AtmosphereResource resource) {
r.set(resource);
resource.addEventListener(new AtmosphereResourceEventListenerAdapter() {
@Override
public void onSuspend(AtmosphereResourceEvent event) {
event.getResource().getBroadcaster().broadcast("message");
}
}).suspend();
}
@Message
public void message(AtmosphereResourceEvent event) {
message.set(event.getMessage().toString());
}
}
@Test
public void testMessage() throws IOException, ServletException {
AtmosphereRequest request = new AtmosphereRequest.Builder().pathInfo("/e").method("GET").build();
framework.doCometSupport(request, AtmosphereResponse.newInstance());
assertNotNull(r.get());
r.get().resume();
assertNotNull(message.get());
assertNotNull(message.get(), "message");
}
}
| true | true | public void create() throws Throwable {
framework = new AtmosphereFramework();
framework.setDefaultBroadcasterClassName(SimpleBroadcaster.class.getName()) ;
String name = new File(".").getAbsolutePath();
framework.setLibPath(name.substring(0, name.length() - 1) + "/modules/cpr/target/");
framework.setAsyncSupport(new AsynchronousProcessor(framework.getAtmosphereConfig()) {
@Override
public Action service(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
return suspended(req, res);
}
public void action(AtmosphereResourceImpl r) {
try {
resumed(r.getRequest(), r.getResponse());
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}).init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
});
}
| public void create() throws Throwable {
framework = new AtmosphereFramework();
framework.setDefaultBroadcasterClassName(SimpleBroadcaster.class.getName()) ;
String name = new File(".").getAbsolutePath();
framework.setLibPath(name.substring(0, name.length() - 1) + "/target/");
framework.setAsyncSupport(new AsynchronousProcessor(framework.getAtmosphereConfig()) {
@Override
public Action service(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
return suspended(req, res);
}
public void action(AtmosphereResourceImpl r) {
try {
resumed(r.getRequest(), r.getResponse());
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
}
}).init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
});
}
|
diff --git a/src/it/groovydoc/src/test/java/gmavenplus/SomeClassTest.java b/src/it/groovydoc/src/test/java/gmavenplus/SomeClassTest.java
index 36c46b51..13ca0151 100644
--- a/src/it/groovydoc/src/test/java/gmavenplus/SomeClassTest.java
+++ b/src/it/groovydoc/src/test/java/gmavenplus/SomeClassTest.java
@@ -1,32 +1,32 @@
/*
* Copyright (C) 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gmavenplus;
import java.io.File;
import org.junit.Assert;
import org.junit.Test;
public class SomeClassTest {
@Test
public void testSomeMethod() {
- File generatedGroovydoc = new File("target/gapidocs/DefaultPackage/SomeClass.html");
+ File generatedGroovydoc = new File("target/gapidocs/gmavenplus/SomeClass.html");
Assert.assertTrue(generatedGroovydoc.exists());
}
}
| true | true | public void testSomeMethod() {
File generatedGroovydoc = new File("target/gapidocs/DefaultPackage/SomeClass.html");
Assert.assertTrue(generatedGroovydoc.exists());
}
| public void testSomeMethod() {
File generatedGroovydoc = new File("target/gapidocs/gmavenplus/SomeClass.html");
Assert.assertTrue(generatedGroovydoc.exists());
}
|
diff --git a/src/test/java/org/elasticsearch/index/mapper/geo/GeoEncodingTests.java b/src/test/java/org/elasticsearch/index/mapper/geo/GeoEncodingTests.java
index f02e15d8337..f52363e89ae 100644
--- a/src/test/java/org/elasticsearch/index/mapper/geo/GeoEncodingTests.java
+++ b/src/test/java/org/elasticsearch/index/mapper/geo/GeoEncodingTests.java
@@ -1,48 +1,48 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper.geo;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.DistanceUnit.Distance;
import org.elasticsearch.test.ElasticsearchTestCase;
import java.util.Arrays;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class GeoEncodingTests extends ElasticsearchTestCase {
public void test() {
for (int i = 0; i < 10000; ++i) {
final double lat = randomDouble() * 180 - 90;
final double lon = randomDouble() * 360 - 180;
- final Distance precision = new Distance(randomDouble() * 10, randomFrom(Arrays.asList(DistanceUnit.MILLIMETERS, DistanceUnit.METERS, DistanceUnit.KILOMETERS)));
+ final Distance precision = new Distance(1+(randomDouble() * 9), randomFrom(Arrays.asList(DistanceUnit.MILLIMETERS, DistanceUnit.METERS, DistanceUnit.KILOMETERS)));
final GeoPointFieldMapper.Encoding encoding = GeoPointFieldMapper.Encoding.of(precision);
assertThat(encoding.precision().convert(DistanceUnit.METERS).value, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
final GeoPoint geoPoint = encoding.decode(encoding.encodeCoordinate(lat), encoding.encodeCoordinate(lon), new GeoPoint());
final double error = GeoDistance.PLANE.calculate(lat, lon, geoPoint.lat(), geoPoint.lon(), DistanceUnit.METERS);
assertThat(error, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
}
}
}
| true | true | public void test() {
for (int i = 0; i < 10000; ++i) {
final double lat = randomDouble() * 180 - 90;
final double lon = randomDouble() * 360 - 180;
final Distance precision = new Distance(randomDouble() * 10, randomFrom(Arrays.asList(DistanceUnit.MILLIMETERS, DistanceUnit.METERS, DistanceUnit.KILOMETERS)));
final GeoPointFieldMapper.Encoding encoding = GeoPointFieldMapper.Encoding.of(precision);
assertThat(encoding.precision().convert(DistanceUnit.METERS).value, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
final GeoPoint geoPoint = encoding.decode(encoding.encodeCoordinate(lat), encoding.encodeCoordinate(lon), new GeoPoint());
final double error = GeoDistance.PLANE.calculate(lat, lon, geoPoint.lat(), geoPoint.lon(), DistanceUnit.METERS);
assertThat(error, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
}
}
| public void test() {
for (int i = 0; i < 10000; ++i) {
final double lat = randomDouble() * 180 - 90;
final double lon = randomDouble() * 360 - 180;
final Distance precision = new Distance(1+(randomDouble() * 9), randomFrom(Arrays.asList(DistanceUnit.MILLIMETERS, DistanceUnit.METERS, DistanceUnit.KILOMETERS)));
final GeoPointFieldMapper.Encoding encoding = GeoPointFieldMapper.Encoding.of(precision);
assertThat(encoding.precision().convert(DistanceUnit.METERS).value, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
final GeoPoint geoPoint = encoding.decode(encoding.encodeCoordinate(lat), encoding.encodeCoordinate(lon), new GeoPoint());
final double error = GeoDistance.PLANE.calculate(lat, lon, geoPoint.lat(), geoPoint.lon(), DistanceUnit.METERS);
assertThat(error, lessThanOrEqualTo(precision.convert(DistanceUnit.METERS).value));
}
}
|
diff --git a/cruisecontrol/reporting/dashboard/test/unit/net/sourceforge/cruisecontrol/dashboard/testhelpers/FilesystemUtils.java b/cruisecontrol/reporting/dashboard/test/unit/net/sourceforge/cruisecontrol/dashboard/testhelpers/FilesystemUtils.java
index 3ce9d1c6..ef970942 100644
--- a/cruisecontrol/reporting/dashboard/test/unit/net/sourceforge/cruisecontrol/dashboard/testhelpers/FilesystemUtils.java
+++ b/cruisecontrol/reporting/dashboard/test/unit/net/sourceforge/cruisecontrol/dashboard/testhelpers/FilesystemUtils.java
@@ -1,124 +1,124 @@
/********************************************************************************
* CruiseControl, a Continuous Integration Toolkit
* Copyright (c) 2007, ThoughtWorks, Inc.
* 200 E. Randolph, 25th Floor
* Chicago, IL 60601 USA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* + Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
package net.sourceforge.cruisecontrol.dashboard.testhelpers;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public final class FilesystemUtils {
private static final String ROOT = "target" + File.separator + "testfiles";
private FilesystemUtils() {
}
public static File createDirectory(String directoryName) {
File directory = new File(getTestRootDir(), directoryName);
deleteDirectory(directory);
directory.mkdir();
directory.deleteOnExit();
return directory;
}
private static void deleteDirectory(File directory) {
try {
FileUtils.deleteDirectory(directory);
} catch (IOException e) {
}
}
public static File createDirectory(String directoryName, String parent) {
File directory = new File(getTestRootDir(), parent + File.separator + directoryName);
deleteDirectory(directory);
directory.mkdir();
directory.deleteOnExit();
return directory;
}
public static File getTestRootDir() {
File root = new File(ROOT);
if (!root.exists() && !root.mkdir()) {
throw new RuntimeException("Failed to create directory for test data [" + root.getAbsolutePath() + "]");
}
return root;
}
public static File createFile(String filename, File directory) throws IOException {
final File file = new File(directory, filename);
// attempt workaround for intermitent w2k error:
// java.io.IOException: Access is denied
// at java.io.WinNTFileSystem.createFileExclusively(Native Method)
// at java.io.File.createNewFile(File.java:883)
- // at net.sourceforge.cruisecontrol.dashboard.testhelpers.FilesystemUtils.createFile(FilesystemUtils.java:98)
+ // at net.sourceforge.cruisecontrol.dashboard.testhelpers.FilesystemUtils.createFile(FilesystemUtils.java:94)
// ...
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6198547
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6325169
int count = 0;
IOException lastIOException = null;
do {
try {
file.createNewFile();
} catch (IOException e) {
lastIOException = e;
Thread.yield();
}
count++;
} while (!file.exists() && count < 3);
if (!file.exists()) {
if (lastIOException != null) {
- throw lastIOException;
+ throw new RuntimeException("Error creating file: " + file.getAbsolutePath(), lastIOException);
} else {
throw new RuntimeException("Error creating file: " + file.getAbsolutePath());
}
}
file.deleteOnExit();
return file;
}
public static File createFile(String filename) throws IOException {
File file = new File(ROOT + File.separator + filename);
file.createNewFile();
file.deleteOnExit();
return file;
}
}
| false | true | public static File createFile(String filename, File directory) throws IOException {
final File file = new File(directory, filename);
// attempt workaround for intermitent w2k error:
// java.io.IOException: Access is denied
// at java.io.WinNTFileSystem.createFileExclusively(Native Method)
// at java.io.File.createNewFile(File.java:883)
// at net.sourceforge.cruisecontrol.dashboard.testhelpers.FilesystemUtils.createFile(FilesystemUtils.java:98)
// ...
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6198547
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6325169
int count = 0;
IOException lastIOException = null;
do {
try {
file.createNewFile();
} catch (IOException e) {
lastIOException = e;
Thread.yield();
}
count++;
} while (!file.exists() && count < 3);
if (!file.exists()) {
if (lastIOException != null) {
throw lastIOException;
} else {
throw new RuntimeException("Error creating file: " + file.getAbsolutePath());
}
}
file.deleteOnExit();
return file;
}
| public static File createFile(String filename, File directory) throws IOException {
final File file = new File(directory, filename);
// attempt workaround for intermitent w2k error:
// java.io.IOException: Access is denied
// at java.io.WinNTFileSystem.createFileExclusively(Native Method)
// at java.io.File.createNewFile(File.java:883)
// at net.sourceforge.cruisecontrol.dashboard.testhelpers.FilesystemUtils.createFile(FilesystemUtils.java:94)
// ...
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6198547
// see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6325169
int count = 0;
IOException lastIOException = null;
do {
try {
file.createNewFile();
} catch (IOException e) {
lastIOException = e;
Thread.yield();
}
count++;
} while (!file.exists() && count < 3);
if (!file.exists()) {
if (lastIOException != null) {
throw new RuntimeException("Error creating file: " + file.getAbsolutePath(), lastIOException);
} else {
throw new RuntimeException("Error creating file: " + file.getAbsolutePath());
}
}
file.deleteOnExit();
return file;
}
|
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java
index f863176..9553671 100755
--- a/src/com/android/nfc/NfcService.java
+++ b/src/com/android/nfc/NfcService.java
@@ -1,2632 +1,2632 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nfc;
import com.android.internal.nfc.LlcpServiceSocket;
import com.android.internal.nfc.LlcpSocket;
import com.android.nfc.mytag.MyTagClient;
import com.android.nfc.mytag.MyTagServer;
import android.app.Application;
import android.app.StatusBarManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.ErrorCodes;
import android.nfc.FormatException;
import android.nfc.ILlcpConnectionlessSocket;
import android.nfc.ILlcpServiceSocket;
import android.nfc.ILlcpSocket;
import android.nfc.INfcAdapter;
import android.nfc.INfcTag;
import android.nfc.IP2pInitiator;
import android.nfc.IP2pTarget;
import android.nfc.LlcpPacket;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.INfcSecureElement;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Timer;
import java.util.TimerTask;
public class NfcService extends Application {
static final boolean DBG = false;
private static final String MY_TAG_FILE_NAME = "mytag";
static {
System.loadLibrary("nfc_jni");
}
public static final String SERVICE_NAME = "nfc";
private static final String TAG = "NfcService";
private static final String NFC_PERM = android.Manifest.permission.NFC;
private static final String NFC_PERM_ERROR = "NFC permission required";
private static final String ADMIN_PERM = android.Manifest.permission.WRITE_SECURE_SETTINGS;
private static final String ADMIN_PERM_ERROR = "WRITE_SECURE_SETTINGS permission required";
private static final String PREF = "NfcServicePrefs";
private static final String PREF_NFC_ON = "nfc_on";
private static final boolean NFC_ON_DEFAULT = true;
private static final String PREF_SECURE_ELEMENT_ON = "secure_element_on";
private static final boolean SECURE_ELEMENT_ON_DEFAULT = false;
private static final String PREF_SECURE_ELEMENT_ID = "secure_element_id";
private static final int SECURE_ELEMENT_ID_DEFAULT = 0;
private static final String PREF_LLCP_LTO = "llcp_lto";
private static final int LLCP_LTO_DEFAULT = 150;
private static final int LLCP_LTO_MAX = 255;
/** Maximum Information Unit */
private static final String PREF_LLCP_MIU = "llcp_miu";
private static final int LLCP_MIU_DEFAULT = 128;
private static final int LLCP_MIU_MAX = 2176;
/** Well Known Service List */
private static final String PREF_LLCP_WKS = "llcp_wks";
private static final int LLCP_WKS_DEFAULT = 1;
private static final int LLCP_WKS_MAX = 15;
private static final String PREF_LLCP_OPT = "llcp_opt";
private static final int LLCP_OPT_DEFAULT = 0;
private static final int LLCP_OPT_MAX = 3;
private static final String PREF_DISCOVERY_A = "discovery_a";
private static final boolean DISCOVERY_A_DEFAULT = true;
private static final String PREF_DISCOVERY_B = "discovery_b";
private static final boolean DISCOVERY_B_DEFAULT = true;
private static final String PREF_DISCOVERY_F = "discovery_f";
private static final boolean DISCOVERY_F_DEFAULT = true;
private static final String PREF_DISCOVERY_15693 = "discovery_15693";
private static final boolean DISCOVERY_15693_DEFAULT = true;
private static final String PREF_DISCOVERY_NFCIP = "discovery_nfcip";
private static final boolean DISCOVERY_NFCIP_DEFAULT = true;
/** NFC Reader Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_READER = 0;
/** Card Emulation Discovery mode for enableDiscovery() */
private static final int DISCOVERY_MODE_CARD_EMULATION = 2;
private static final int LLCP_SERVICE_SOCKET_TYPE = 0;
private static final int LLCP_SOCKET_TYPE = 1;
private static final int LLCP_CONNECTIONLESS_SOCKET_TYPE = 2;
private static final int LLCP_SOCKET_NB_MAX = 5; // Maximum number of socket managed
private static final int LLCP_RW_MAX_VALUE = 15; // Receive Window
private static final int PROPERTY_LLCP_LTO = 0;
private static final String PROPERTY_LLCP_LTO_VALUE = "llcp.lto";
private static final int PROPERTY_LLCP_MIU = 1;
private static final String PROPERTY_LLCP_MIU_VALUE = "llcp.miu";
private static final int PROPERTY_LLCP_WKS = 2;
private static final String PROPERTY_LLCP_WKS_VALUE = "llcp.wks";
private static final int PROPERTY_LLCP_OPT = 3;
private static final String PROPERTY_LLCP_OPT_VALUE = "llcp.opt";
private static final int PROPERTY_NFC_DISCOVERY_A = 4;
private static final String PROPERTY_NFC_DISCOVERY_A_VALUE = "discovery.iso14443A";
private static final int PROPERTY_NFC_DISCOVERY_B = 5;
private static final String PROPERTY_NFC_DISCOVERY_B_VALUE = "discovery.iso14443B";
private static final int PROPERTY_NFC_DISCOVERY_F = 6;
private static final String PROPERTY_NFC_DISCOVERY_F_VALUE = "discovery.felica";
private static final int PROPERTY_NFC_DISCOVERY_15693 = 7;
private static final String PROPERTY_NFC_DISCOVERY_15693_VALUE = "discovery.iso15693";
private static final int PROPERTY_NFC_DISCOVERY_NFCIP = 8;
private static final String PROPERTY_NFC_DISCOVERY_NFCIP_VALUE = "discovery.nfcip";
static final int MSG_NDEF_TAG = 0;
static final int MSG_CARD_EMULATION = 1;
static final int MSG_LLCP_LINK_ACTIVATION = 2;
static final int MSG_LLCP_LINK_DEACTIVATED = 3;
static final int MSG_TARGET_DESELECTED = 4;
static final int MSG_SHOW_MY_TAG_ICON = 5;
static final int MSG_HIDE_MY_TAG_ICON = 6;
static final int MSG_MOCK_NDEF = 7;
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
private final LinkedList<RegisteredSocket> mRegisteredSocketList = new LinkedList<RegisteredSocket>();
private int mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
private int mGeneratedSocketHandle = 0;
private int mNbSocketCreated = 0;
private volatile boolean mIsNfcEnabled = false;
private int mSelectedSeId = 0;
private boolean mNfcSecureElementState;
// Secure element
private Timer mTimerOpenSmx;
private boolean isClosed = false;
private boolean isOpened = false;
private boolean mOpenSmxPending = false;
private NativeNfcSecureElement mSecureElement;
private int mSecureElementHandle;
// fields below are used in multiple threads and protected by synchronized(this)
private final HashMap<Integer, Object> mObjectMap = new HashMap<Integer, Object>();
private final HashMap<Integer, Object> mSocketMap = new HashMap<Integer, Object>();
private boolean mScreenOn;
// fields below are final after onCreate()
private Context mContext;
private NativeNfcManager mManager;
private SharedPreferences mPrefs;
private SharedPreferences.Editor mPrefsEditor;
private PowerManager.WakeLock mWakeLock;
private MyTagServer mMyTagServer;
private MyTagClient mMyTagClient;
private static NfcService sService;
public static NfcService getInstance() {
return sService;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting NFC service");
sService = this;
mContext = this;
mManager = new NativeNfcManager(mContext, this);
mManager.initializeNativeStructure();
mMyTagServer = new MyTagServer();
mMyTagClient = new MyTagClient(this);
mSecureElement = new NativeNfcSecureElement();
mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
mPrefsEditor = mPrefs.edit();
mIsNfcEnabled = false; // real preference read later
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mScreenOn = pm.isScreenOn();
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NfcService");
ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
IntentFilter filter = new IntentFilter(NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
mContext.registerReceiver(mReceiver, filter);
Thread t = new Thread() {
@Override
public void run() {
boolean nfc_on = mPrefs.getBoolean(PREF_NFC_ON, NFC_ON_DEFAULT);
if (nfc_on) {
_enable(false);
}
}
};
t.start();
}
@Override
public void onTerminate() {
super.onTerminate();
// NFC application is persistent, it should not be destroyed by framework
Log.wtf(TAG, "NFC service is under attack!");
}
private final INfcAdapter.Stub mNfcAdapter = new INfcAdapter.Stub() {
/** Protected by "this" */
NdefMessage mLocalMessage = null;
@Override
public boolean enable() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean isSuccess = false;
boolean previouslyEnabled = isEnabled();
if (!previouslyEnabled) {
reset();
isSuccess = _enable(previouslyEnabled);
}
return isSuccess;
}
@Override
public boolean disable() throws RemoteException {
boolean isSuccess = false;
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
boolean previouslyEnabled = isEnabled();
if (DBG) Log.d(TAG, "Disabling NFC. previous=" + previouslyEnabled);
if (previouslyEnabled) {
/* tear down the my tag server */
mMyTagServer.stop();
isSuccess = mManager.deinitialize();
if (DBG) Log.d(TAG, "NFC success of deinitialize = " + isSuccess);
if (isSuccess) {
mIsNfcEnabled = false;
}
}
updateNfcOnSetting(previouslyEnabled);
return isSuccess;
}
@Override
public int createLlcpConnectionlessSocket(int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* Check SAP is not already used */
/* Check nb socket created */
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* Store the socket handle */
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpConnectionlessSocket socket;
socket = mManager.doCreateLlcpConnectionlessSocket(sap);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
return sockeHandle;
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
NativeLlcpConnectionlessSocket socket = new NativeLlcpConnectionlessSocket(sap);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(
LLCP_CONNECTIONLESS_SOCKET_TYPE, sockeHandle, sap);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int createLlcpServiceSocket(int sap, String sn, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
NativeLlcpServiceSocket socket;
socket = mManager.doCreateLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/* socket creation error - update the socket handle counter */
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Service Name */
if (!CheckSocketServiceName(sn)) {
return ErrorCodes.ERROR_SERVICE_NAME_USED;
}
/* Check socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpServiceSocket socket = new NativeLlcpServiceSocket(sap, sn, miu, rw,
linearBufferLength);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SERVICE_SOCKET_TYPE,
sockeHandle, sap, sn, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle += 1;
if (DBG) Log.d(TAG, "Llcp Service Socket Handle =" + sockeHandle);
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength)
throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
int sockeHandle = mGeneratedSocketHandle;
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
if (DBG) Log.d(TAG, "creating llcp socket while activated");
NativeLlcpSocket socket;
socket = mManager.doCreateLlcpSocket(sap, miu, rw, linearBufferLength);
if (socket != null) {
synchronized(NfcService.this) {
/* Update the number of socket created */
mNbSocketCreated++;
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
}
} else {
/*
* socket creation error - update the socket handle
* generation
*/
mGeneratedSocketHandle -= 1;
/* Get Error Status */
int errorStatus = mManager.doGetLastError();
Log.d(TAG, "failed to create llcp socket: " + ErrorCodes.asString(errorStatus));
switch (errorStatus) {
case ErrorCodes.ERROR_BUFFER_TO_SMALL:
return ErrorCodes.ERROR_BUFFER_TO_SMALL;
case ErrorCodes.ERROR_INSUFFICIENT_RESOURCES:
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
default:
return ErrorCodes.ERROR_SOCKET_CREATION;
}
}
} else {
if (DBG) Log.d(TAG, "registering llcp socket while not activated");
/* Check SAP is not already used */
if (!CheckSocketSap(sap)) {
return ErrorCodes.ERROR_SAP_USED;
}
/* Check Socket options */
if (!CheckSocketOptions(miu, rw, linearBufferLength)) {
return ErrorCodes.ERROR_SOCKET_OPTIONS;
}
NativeLlcpSocket socket = new NativeLlcpSocket(sap, miu, rw);
synchronized(NfcService.this) {
/* Add the socket into the socket map */
mSocketMap.put(sockeHandle, socket);
/* Update the number of socket created */
mNbSocketCreated++;
}
/* Create new registered socket */
RegisteredSocket registeredSocket = new RegisteredSocket(LLCP_SOCKET_TYPE,
sockeHandle, sap, miu, rw, linearBufferLength);
/* Put this socket into a list of registered socket */
mRegisteredSocketList.add(registeredSocket);
}
/* update socket handle generation */
mGeneratedSocketHandle++;
return sockeHandle;
} else {
/* No socket available */
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public int deselectSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == 0) {
return ErrorCodes.ERROR_NO_SE_CONNECTED;
}
mManager.doDeselectSecureElement(mSelectedSeId);
mNfcSecureElementState = false;
mSelectedSeId = 0;
/* store preference */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, false);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, 0);
mPrefsEditor.apply();
return ErrorCodes.SUCCESS;
}
@Override
public ILlcpConnectionlessSocket getLlcpConnectionlessInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpConnectionlessSocketService;
}
@Override
public ILlcpSocket getLlcpInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpSocket;
}
@Override
public ILlcpServiceSocket getLlcpServiceInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mLlcpServerSocketService;
}
@Override
public INfcTag getNfcTagInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mNfcTagService;
}
@Override
public IP2pInitiator getP2pInitiatorInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pInitiatorService;
}
@Override
public IP2pTarget getP2pTargetInterface() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mP2pTargetService;
}
public INfcSecureElement getNfcSecureElementInterface() {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
return mSecureElementService;
}
@Override
public String getProperties(String param) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
if (param == null) {
return null;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
return Integer.toString(mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT));
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
return Boolean.toString(mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT));
} else {
return "Unknown property";
}
}
@Override
public int[] getSecureElementList() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
int[] list = null;
if (mIsNfcEnabled == true) {
list = mManager.doGetSecureElementList();
}
return list;
}
@Override
public int getSelectedSecureElement() throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
return mSelectedSeId;
}
@Override
public boolean isEnabled() throws RemoteException {
return mIsNfcEnabled;
}
@Override
public void openTagConnection(Tag tag) throws RemoteException {
// TODO: Remove obsolete code
}
@Override
public int selectSecureElement(int seId) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mSelectedSeId == seId) {
return ErrorCodes.ERROR_SE_ALREADY_SELECTED;
}
if (mSelectedSeId != 0) {
return ErrorCodes.ERROR_SE_CONNECTED;
}
mSelectedSeId = seId;
mManager.doSelectSecureElement(mSelectedSeId);
/* store */
mPrefsEditor.putBoolean(PREF_SECURE_ELEMENT_ON, true);
mPrefsEditor.putInt(PREF_SECURE_ELEMENT_ID, mSelectedSeId);
mPrefsEditor.apply();
mNfcSecureElementState = true;
return ErrorCodes.SUCCESS;
}
@Override
public int setProperties(String param, String value) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
if (isEnabled()) {
return ErrorCodes.ERROR_NFC_ON;
}
int val;
/* Check params validity */
if (param == null || value == null) {
return ErrorCodes.ERROR_INVALID_PARAM;
}
if (param.equals(PROPERTY_LLCP_LTO_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_LTO_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_LTO, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_LTO, val);
} else if (param.equals(PROPERTY_LLCP_MIU_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if ((val < LLCP_MIU_DEFAULT) || (val > LLCP_MIU_MAX))
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_MIU, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_MIU, val);
} else if (param.equals(PROPERTY_LLCP_WKS_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_WKS_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_WKS, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_WKS, val);
} else if (param.equals(PROPERTY_LLCP_OPT_VALUE)) {
val = Integer.parseInt(value);
/* Check params */
if (val > LLCP_OPT_MAX)
return ErrorCodes.ERROR_INVALID_PARAM;
/* Store value */
mPrefsEditor.putInt(PREF_LLCP_OPT, val);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_LLCP_OPT, val);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_A_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_A, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_B_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_B, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_F_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_F, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_15693_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_15693, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693, b ? 1 : 0);
} else if (param.equals(PROPERTY_NFC_DISCOVERY_NFCIP_VALUE)) {
boolean b = Boolean.parseBoolean(value);
/* Store value */
mPrefsEditor.putBoolean(PREF_DISCOVERY_NFCIP, b);
mPrefsEditor.apply();
/* Update JNI */
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP, b ? 1 : 0);
} else {
return ErrorCodes.ERROR_INVALID_PARAM;
}
return ErrorCodes.SUCCESS;
}
@Override
public NdefMessage localGet() throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
synchronized (this) {
return mLocalMessage;
}
}
@Override
public void localSet(NdefMessage message) throws RemoteException {
mContext.enforceCallingOrSelfPermission(ADMIN_PERM, ADMIN_PERM_ERROR);
synchronized (this) {
mLocalMessage = message;
Context context = NfcService.this.getApplicationContext();
// Send a message to the UI thread to show or hide the icon so the requests are
// serialized and the icon can't get out of sync with reality.
if (message != null) {
FileOutputStream out = null;
try {
out = context.openFileOutput(MY_TAG_FILE_NAME, Context.MODE_PRIVATE);
byte[] bytes = message.toByteArray();
if (bytes.length == 0) {
Log.w(TAG, "Setting a empty mytag");
}
out.write(bytes);
} catch (IOException e) {
Log.e(TAG, "Could not write mytag file", e);
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
// Ignore
}
}
// Only show the icon if NFC is enabled.
if (mIsNfcEnabled) {
sendMessage(MSG_SHOW_MY_TAG_ICON, null);
}
} else {
context.deleteFile(MY_TAG_FILE_NAME);
sendMessage(MSG_HIDE_MY_TAG_ICON, null);
}
}
}
};
private final ILlcpSocket mLlcpSocket = new ILlcpSocket.Stub() {
private final int CONNECT_FLAG = 0x01;
private final int CLOSE_FLAG = 0x02;
private final int RECV_FLAG = 0x04;
private final int SEND_FLAG = 0x08;
private int concurrencyFlags;
private Object sync;
@Override
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
return ErrorCodes.SUCCESS;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int connect(int nativeHandle, int sap) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnect(sap);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int connectByName(int nativeHandle, String sn) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doConnectBy(sn);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int getLocalSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
@Override
public int getLocalSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getMiu();
} else {
return 0;
}
}
@Override
public int getLocalSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getRw();
} else {
return 0;
}
}
@Override
public int getRemoteSocketMiu(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketMiu() != 0) {
return socket.doGetRemoteSocketMiu();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
@Override
public int getRemoteSocketRw(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
if (socket.doGetRemoteSocketRw() != 0) {
return socket.doGetRemoteSocketRw();
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
} else {
return ErrorCodes.ERROR_SOCKET_NOT_CONNECTED;
}
}
@Override
public int receive(int nativeHandle, byte[] receiveBuffer) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
int receiveLength = 0;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
receiveLength = socket.doReceive(receiveBuffer);
if (receiveLength != 0) {
return receiveLength;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSend(data);
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
};
private final ILlcpServiceSocket mLlcpServerSocketService = new ILlcpServiceSocket.Stub() {
@Override
public int accept(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
NativeLlcpSocket clientSocket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
if (mNbSocketCreated < LLCP_SOCKET_NB_MAX) {
/* find the socket in the hmap */
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
clientSocket = socket.doAccept(socket.getMiu(),
socket.getRw(), socket.getLinearBufferLength());
if (clientSocket != null) {
/* Add the socket into the socket map */
synchronized(this) {
mSocketMap.put(clientSocket.getHandle(), clientSocket);
mNbSocketCreated++;
}
return clientSocket.getHandle();
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_INSUFFICIENT_RESOURCES;
}
}
@Override
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpServiceSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
boolean closed = false;
socket = (NativeLlcpServiceSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
closed = true;
}
} else {
closed = true;
}
}
// If the socket is closed remove it from the socket lists
if (closed) {
synchronized (this) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
}
}
}
};
private final ILlcpConnectionlessSocket mLlcpConnectionlessSocketService = new ILlcpConnectionlessSocket.Stub() {
@Override
public void close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
if (mLlcpLinkState == NfcAdapter.LLCP_LINK_STATE_ACTIVATED) {
isSuccess = socket.doClose();
if (isSuccess) {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
} else {
/* Remove the socket closed from the hmap */
RemoveSocket(nativeHandle);
/* Remove registered socket from the list */
RemoveRegisteredSocket(nativeHandle);
/* Update mNbSocketCreated */
mNbSocketCreated--;
}
}
}
@Override
public int getSap(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
return socket.getSap();
} else {
return 0;
}
}
@Override
public LlcpPacket receiveFrom(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
LlcpPacket packet;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
packet = socket.doReceiveFrom(socket.getLinkMiu());
if (packet != null) {
return packet;
}
return null;
} else {
return null;
}
}
@Override
public int sendTo(int nativeHandle, LlcpPacket packet) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeLlcpConnectionlessSocket socket = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the socket in the hmap */
socket = (NativeLlcpConnectionlessSocket) findSocket(nativeHandle);
if (socket != null) {
isSuccess = socket.doSendTo(packet.getRemoteSap(), packet.getDataBuffer());
if (isSuccess) {
return ErrorCodes.SUCCESS;
} else {
return ErrorCodes.ERROR_IO;
}
} else {
return ErrorCodes.ERROR_IO;
}
}
};
private final INfcTag mNfcTagService = new INfcTag.Stub() {
@Override
public int close(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
/* Remove the device from the hmap */
unregisterObject(nativeHandle);
tag.disconnect();
return ErrorCodes.SUCCESS;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
return ErrorCodes.ERROR_DISCONNECT;
}
@Override
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_DISCONNECT;
}
// TODO: register the tag as being locked rather than really connect
return ErrorCodes.SUCCESS;
}
@Override
public int[] getTechList(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
NativeNfcTag tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
return tag.getTechList();
}
return null;
}
@Override
public byte[] getUid(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
byte[] uid;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
uid = tag.getUid();
return uid;
}
return null;
}
@Override
public boolean isPresent(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return false;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return false;
}
return tag.presenceCheck();
}
@Override
public boolean isNdef(int nativeHandle) throws RemoteException {
NativeNfcTag tag = null;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
isSuccess = tag.checkNdef();
}
return isSuccess;
}
@Override
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag = null;
byte[] response;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
response = tag.transceive(data);
return response;
}
return null;
}
@Override
public NdefMessage read(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag != null) {
byte[] buf = tag.read();
if (buf == null)
return null;
/* Create an NdefMessage */
try {
return new NdefMessage(buf);
} catch (FormatException e) {
return null;
}
}
return null;
}
@Override
public int write(int nativeHandle, NdefMessage msg) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeNfcTag tag;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the tag in the hmap */
tag = (NativeNfcTag) findObject(nativeHandle);
if (tag == null) {
return ErrorCodes.ERROR_IO;
}
if (tag.write(msg.toByteArray())) {
return ErrorCodes.SUCCESS;
}
else {
return ErrorCodes.ERROR_IO;
}
}
@Override
public int getLastError(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getModeHint(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
@Override
public int makeReadOnly(int nativeHandle) throws RemoteException {
// TODO Auto-generated method stub
return 0;
}
};
private final IP2pInitiator mP2pInitiatorService = new IP2pInitiator.Stub() {
@Override
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
@Override
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
@Override
public byte[] receive(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doReceive();
if (buff == null)
return null;
return buff;
}
/* Restart polling loop for notification */
maybeEnableDiscovery();
return null;
}
@Override
public boolean send(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
isSuccess = device.doSend(data);
}
return isSuccess;
}
};
private final IP2pTarget mP2pTargetService = new IP2pTarget.Stub() {
@Override
public int connect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (device.doConnect()) {
return ErrorCodes.SUCCESS;
}
}
return ErrorCodes.ERROR_CONNECT;
}
@Override
public boolean disconnect(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
boolean isSuccess = false;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return isSuccess;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
if (isSuccess = device.doDisconnect()) {
/* remove the device from the hmap */
unregisterObject(nativeHandle);
/* Restart polling loop for notification */
maybeEnableDiscovery();
}
}
return isSuccess;
}
@Override
public byte[] getGeneralBytes(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.getGeneralBytes();
if (buff == null)
return null;
return buff;
}
return null;
}
@Override
public int getMode(int nativeHandle) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
return device.getMode();
}
return ErrorCodes.ERROR_INVALID_PARAM;
}
@Override
public byte[] transceive(int nativeHandle, byte[] data) throws RemoteException {
mContext.enforceCallingOrSelfPermission(NFC_PERM, NFC_PERM_ERROR);
NativeP2pDevice device;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
/* find the device in the hmap */
device = (NativeP2pDevice) findObject(nativeHandle);
if (device != null) {
byte[] buff = device.doTransceive(data);
if (buff == null)
return null;
return buff;
}
return null;
}
};
private INfcSecureElement mSecureElementService = new INfcSecureElement.Stub() {
public int openSecureElementConnection() throws RemoteException {
Log.d(TAG, "openSecureElementConnection");
int handle;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return 0;
}
// Check in an open is already pending
if (mOpenSmxPending) {
return 0;
}
handle = mSecureElement.doOpenSecureElementConnection();
if (handle == 0) {
mOpenSmxPending = false;
} else {
mSecureElementHandle = handle;
/* Start timer */
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
/* Update state */
isOpened = true;
isClosed = false;
mOpenSmxPending = true;
}
return handle;
}
public int closeSecureElementConnection(int nativeHandle)
throws RemoteException {
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return ErrorCodes.ERROR_NOT_INITIALIZED;
}
// Check if the SE connection is closed
if (isClosed) {
return -1;
}
// Check if the SE connection is opened
if (!isOpened) {
return -1;
}
if (mSecureElement.doDisconnect(nativeHandle)) {
/* Stop timer */
mTimerOpenSmx.cancel();
/* Restart polling loop for notification */
mManager.enableDiscovery(DISCOVERY_MODE_READER);
/* Update state */
isOpened = false;
isClosed = true;
mOpenSmxPending = false;
return ErrorCodes.SUCCESS;
} else {
/* Stop timer */
mTimerOpenSmx.cancel();
/* Restart polling loop for notification */
mManager.enableDiscovery(DISCOVERY_MODE_READER);
/* Update state */
isOpened = false;
isClosed = true;
mOpenSmxPending = false;
return ErrorCodes.ERROR_DISCONNECT;
}
}
public int[] getSecureElementTechList(int nativeHandle)
throws RemoteException {
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
int[] techList = mSecureElement.doGetTechList(nativeHandle);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return techList;
}
public byte[] getSecureElementUid(int nativeHandle)
throws RemoteException {
byte[] uid;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
uid = mSecureElement.doGetUid(nativeHandle);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return uid;
}
public byte[] exchangeAPDU(int nativeHandle, byte[] data)
throws RemoteException {
byte[] response;
// Check if NFC is enabled
if (!mIsNfcEnabled) {
return null;
}
// Check if the SE connection is closed
if (isClosed) {
return null;
}
// Check if the SE connection is opened
if (!isOpened) {
return null;
}
response = mSecureElement.doTransceive(nativeHandle, data);
/* Stop and Restart timer */
mTimerOpenSmx.cancel();
mTimerOpenSmx = new Timer();
mTimerOpenSmx.schedule(new TimerOpenSecureElement(), 30000);
return response;
}
};
class TimerOpenSecureElement extends TimerTask {
@Override
public void run() {
if (mSecureElementHandle != 0) {
Log.d(TAG, "Open SMX timer expired");
try {
mSecureElementService
.closeSecureElementConnection(mSecureElementHandle);
} catch (RemoteException e) {
}
}
}
}
private boolean _enable(boolean oldEnabledState) {
boolean isSuccess = mManager.initialize();
if (isSuccess) {
applyProperties();
/* Check Secure Element setting */
mNfcSecureElementState = mPrefs.getBoolean(PREF_SECURE_ELEMENT_ON,
SECURE_ELEMENT_ON_DEFAULT);
if (mNfcSecureElementState) {
int secureElementId = mPrefs.getInt(PREF_SECURE_ELEMENT_ID,
SECURE_ELEMENT_ID_DEFAULT);
int[] Se_list = mManager.doGetSecureElementList();
if (Se_list != null) {
for (int i = 0; i < Se_list.length; i++) {
if (Se_list[i] == secureElementId) {
mManager.doSelectSecureElement(Se_list[i]);
mSelectedSeId = Se_list[i];
break;
}
}
}
}
mIsNfcEnabled = true;
/* Start polling loop */
maybeEnableDiscovery();
/* bring up the my tag server */
mMyTagServer.start();
} else {
mIsNfcEnabled = false;
}
updateNfcOnSetting(oldEnabledState);
return isSuccess;
}
/** Enable active tag discovery if screen is on and NFC is enabled */
private synchronized void maybeEnableDiscovery() {
if (mScreenOn && mIsNfcEnabled) {
mManager.enableDiscovery(DISCOVERY_MODE_READER);
}
}
/** Disable active tag discovery if necessary */
private synchronized void maybeDisableDiscovery() {
if (mIsNfcEnabled) {
mManager.disableDiscovery();
}
}
private void applyProperties() {
mManager.doSetProperties(PROPERTY_LLCP_LTO, mPrefs.getInt(PREF_LLCP_LTO, LLCP_LTO_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_MIU, mPrefs.getInt(PREF_LLCP_MIU, LLCP_MIU_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_WKS, mPrefs.getInt(PREF_LLCP_WKS, LLCP_WKS_DEFAULT));
mManager.doSetProperties(PROPERTY_LLCP_OPT, mPrefs.getInt(PREF_LLCP_OPT, LLCP_OPT_DEFAULT));
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_A,
mPrefs.getBoolean(PREF_DISCOVERY_A, DISCOVERY_A_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_B,
mPrefs.getBoolean(PREF_DISCOVERY_B, DISCOVERY_B_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_F,
mPrefs.getBoolean(PREF_DISCOVERY_F, DISCOVERY_F_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_15693,
mPrefs.getBoolean(PREF_DISCOVERY_15693, DISCOVERY_15693_DEFAULT) ? 1 : 0);
mManager.doSetProperties(PROPERTY_NFC_DISCOVERY_NFCIP,
mPrefs.getBoolean(PREF_DISCOVERY_NFCIP, DISCOVERY_NFCIP_DEFAULT) ? 1 : 0);
}
private void updateNfcOnSetting(boolean oldEnabledState) {
int state;
mPrefsEditor.putBoolean(PREF_NFC_ON, mIsNfcEnabled);
mPrefsEditor.apply();
synchronized(this) {
if (oldEnabledState != mIsNfcEnabled) {
Intent intent = new Intent(NfcAdapter.ACTION_ADAPTER_STATE_CHANGE);
intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(NfcAdapter.EXTRA_NEW_BOOLEAN_STATE, mIsNfcEnabled);
mContext.sendBroadcast(intent);
}
if (mIsNfcEnabled) {
Context context = getApplicationContext();
// Set this to null by default. If there isn't a tag on disk
// or if there was an error reading the tag then this will cause
// the status bar icon to be removed.
NdefMessage myTag = null;
FileInputStream input = null;
try {
input = context.openFileInput(MY_TAG_FILE_NAME);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = 0;
while ((read = input.read(buffer)) > 0) {
bytes.write(buffer, 0, read);
}
myTag = new NdefMessage(bytes.toByteArray());
} catch (FileNotFoundException e) {
// Ignore.
} catch (IOException e) {
Log.e(TAG, "Could not read mytag file: ", e);
context.deleteFile(MY_TAG_FILE_NAME);
} catch (FormatException e) {
Log.e(TAG, "Invalid NdefMessage for mytag", e);
context.deleteFile(MY_TAG_FILE_NAME);
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e) {
// Ignore
}
}
try {
mNfcAdapter.localSet(myTag);
} catch (RemoteException e) {
// Ignore
}
} else {
sendMessage(MSG_HIDE_MY_TAG_ICON, null);
}
}
}
// Reset all internals
private synchronized void reset() {
// TODO: none of these appear to be synchronized but are
// read/written from different threads (notably Binder threads)...
// Clear tables
mObjectMap.clear();
mSocketMap.clear();
mRegisteredSocketList.clear();
// Reset variables
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
mNbSocketCreated = 0;
mIsNfcEnabled = false;
mSelectedSeId = 0;
}
private synchronized Object findObject(int key) {
Object device = null;
device = mObjectMap.get(key);
if (device == null) {
Log.w(TAG, "Handle not found !");
}
return device;
}
synchronized void registerTagObject(NativeNfcTag nativeTag) {
mObjectMap.put(nativeTag.getHandle(), nativeTag);
}
synchronized void unregisterObject(int handle) {
mObjectMap.remove(handle);
}
private synchronized Object findSocket(int key) {
Object socket = null;
socket = mSocketMap.get(key);
return socket;
}
private void RemoveSocket(int key) {
mSocketMap.remove(key);
}
private boolean CheckSocketSap(int sap) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sap == registeredSocket.mSap) {
/* SAP already used */
return false;
}
}
return true;
}
private boolean CheckSocketOptions(int miu, int rw, int linearBufferlength) {
if (rw > LLCP_RW_MAX_VALUE || miu < LLCP_MIU_DEFAULT || linearBufferlength < miu) {
return false;
}
return true;
}
private boolean CheckSocketServiceName(String sn) {
/* List of sockets registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (sn.equals(registeredSocket.mServiceName)) {
/* Service Name already used */
return false;
}
}
return true;
}
private void RemoveRegisteredSocket(int nativeHandle) {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
if (registeredSocket.mHandle == nativeHandle) {
/* remove the registered socket from the list */
it.remove();
if (DBG) Log.d(TAG, "socket removed");
}
}
}
/*
* RegisteredSocket class to store the creation request of socket until the
* LLCP link in not activated
*/
private class RegisteredSocket {
private final int mType;
private final int mHandle;
private final int mSap;
private int mMiu;
private int mRw;
private String mServiceName;
private int mlinearBufferLength;
RegisteredSocket(int type, int handle, int sap, String sn, int miu, int rw,
int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mServiceName = sn;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap, int miu, int rw, int linearBufferLength) {
mType = type;
mHandle = handle;
mSap = sap;
mRw = rw;
mMiu = miu;
mlinearBufferLength = linearBufferLength;
}
RegisteredSocket(int type, int handle, int sap) {
mType = type;
mHandle = handle;
mSap = sap;
}
}
/** For use by code in this process */
public LlcpSocket createLlcpSocket(int sap, int miu, int rw, int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpSocket(sap, miu, rw, linearBufferLength);
if (ErrorCodes.isError(handle)) {
Log.e(TAG, "unable to create socket: " + ErrorCodes.asString(handle));
return null;
}
return new LlcpSocket(mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
/** For use by code in this process */
public LlcpServiceSocket createLlcpServiceSocket(int sap, String sn, int miu, int rw,
int linearBufferLength) {
try {
int handle = mNfcAdapter.createLlcpServiceSocket(sap, sn, miu, rw, linearBufferLength);
if (ErrorCodes.isError(handle)) {
Log.e(TAG, "unable to create socket: " + ErrorCodes.asString(handle));
return null;
}
return new LlcpServiceSocket(mLlcpServerSocketService, mLlcpSocket, handle);
} catch (RemoteException e) {
// This will never happen since the code is calling into it's own process
throw new IllegalStateException("unable to talk to myself", e);
}
}
private void activateLlcpLink() {
/* check if sockets are registered */
ListIterator<RegisteredSocket> it = mRegisteredSocketList.listIterator();
if (DBG) Log.d(TAG, "Nb socket resgistered = " + mRegisteredSocketList.size());
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_ACTIVATED;
while (it.hasNext()) {
RegisteredSocket registeredSocket = it.next();
switch (registeredSocket.mType) {
case LLCP_SERVICE_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Service Socket");
if (DBG) Log.d(TAG, "SAP: " + registeredSocket.mSap + ", SN: " + registeredSocket.mServiceName);
NativeLlcpServiceSocket serviceSocket;
serviceSocket = mManager.doCreateLlcpServiceSocket(
registeredSocket.mSap, registeredSocket.mServiceName,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (serviceSocket != null) {
if (DBG) Log.d(TAG, "service socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, serviceSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// NOTE: don't remove this socket from the registered sockets list.
// If it's removed it won't be created the next time an LLCP
// connection is activated and the server won't be found.
break;
case LLCP_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Socket");
NativeLlcpSocket clientSocket;
clientSocket = mManager.doCreateLlcpSocket(registeredSocket.mSap,
registeredSocket.mMiu, registeredSocket.mRw,
registeredSocket.mlinearBufferLength);
if (clientSocket != null) {
if (DBG) Log.d(TAG, "socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, clientSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// This socket has been created, remove it from the registered sockets list.
it.remove();
break;
case LLCP_CONNECTIONLESS_SOCKET_TYPE:
if (DBG) Log.d(TAG, "Registered Llcp Connectionless Socket");
NativeLlcpConnectionlessSocket connectionlessSocket;
connectionlessSocket = mManager.doCreateLlcpConnectionlessSocket(
registeredSocket.mSap);
if (connectionlessSocket != null) {
if (DBG) Log.d(TAG, "connectionless socket created");
/* Add the socket into the socket map */
synchronized(NfcService.this) {
mSocketMap.put(registeredSocket.mHandle, connectionlessSocket);
}
} else {
Log.d(TAG, "FAILED to create service socket");
/* socket creation error - update the socket
* handle counter */
mGeneratedSocketHandle -= 1;
}
// This socket has been created, remove it from the registered sockets list.
it.remove();
break;
}
}
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_ACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP activation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
}
public void sendMockNdefTag(NdefMessage msg) {
sendMessage(MSG_MOCK_NDEF, msg);
}
void sendMessage(int what, Object obj) {
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.obj = obj;
mHandler.sendMessage(msg);
}
final class NfcServiceHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
- /* resume should be done in doConnect */
+ device.doDisconnect();
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
private Intent buildTagIntent(Tag tag, NdefMessage[] msgs) {
Intent intent = new Intent(NfcAdapter.ACTION_TAG_DISCOVERED);
intent.putExtra(NfcAdapter.EXTRA_TAG, tag);
intent.putExtra(NfcAdapter.EXTRA_ID, tag.getId());
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, msgs);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
}
private NfcServiceHandler mHandler = new NfcServiceHandler();
private class EnableDisableDiscoveryTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean... enable) {
if (enable != null && enable.length > 0 && enable[0]) {
synchronized (NfcService.this) {
mScreenOn = true;
maybeEnableDiscovery();
}
} else {
mWakeLock.acquire();
synchronized (NfcService.this) {
mScreenOn = false;
maybeDisableDiscovery();
}
mWakeLock.release();
}
return null;
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
NativeNfcManager.INTERNAL_TARGET_DESELECTED_ACTION)) {
if (DBG) Log.d(TAG, "INERNAL_TARGET_DESELECTED_ACTION");
/* Restart polling loop for notification */
maybeEnableDiscovery();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Perform discovery enable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(true));
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Perform discovery disable in thread to protect against ANR when the
// NFC stack wedges. This is *not* the correct way to fix this issue -
// configuration of the local NFC adapter should be very quick and should
// be safe on the main thread, and the NFC stack should not wedge.
new EnableDisableDiscoveryTask().execute(new Boolean(false));
}
}
};
}
| true | true | public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
/* resume should be done in doConnect */
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
| public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_MOCK_NDEF: {
NdefMessage ndefMsg = (NdefMessage) msg.obj;
Tag tag = Tag.createMockTag(new byte[] { 0x00 },
new int[] { },
new Bundle[] { });
Intent intent = buildTagIntent(tag, new NdefMessage[] { ndefMsg });
Log.d(TAG, "mock NDEF tag, starting corresponding activity");
Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for mock tag");
}
break;
}
case MSG_NDEF_TAG:
if (DBG) Log.d(TAG, "Tag detected, notifying applications");
NativeNfcTag nativeTag = (NativeNfcTag) msg.obj;
if (nativeTag.connect()) {
if (nativeTag.checkNdef()) {
boolean generateEmptyIntent = false;
byte[] buff = nativeTag.read();
if (buff != null) {
NdefMessage[] msgNdef = new NdefMessage[1];
try {
msgNdef[0] = new NdefMessage(buff);
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, msgNdef);
if (DBG) Log.d(TAG, "NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
} catch (FormatException e) {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
} else {
// Create an intent anyway, without NDEF messages
generateEmptyIntent = true;
}
if (generateEmptyIntent) {
// Create an intent with an empty ndef message array
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, new NdefMessage[] { });
if (DBG) Log.d(TAG, "NDEF tag found, but length 0 or invalid format, starting corresponding activity");
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Tag tag = new Tag(nativeTag.getUid(),
nativeTag.getTechList(),
nativeTag.getTechExtras(),
nativeTag.getHandle());
Intent intent = buildTagIntent(tag, null);
if (DBG) Log.d(TAG, "Non-NDEF tag found, starting corresponding activity");
if (DBG) Log.d(TAG, tag.toString());
try {
mContext.startActivity(intent);
registerTagObject(nativeTag);
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found, disconnecting");
nativeTag.disconnect();
}
}
} else {
Log.w(TAG, "Failed to connect to tag");
nativeTag.disconnect();
}
break;
case MSG_CARD_EMULATION:
if (DBG) Log.d(TAG, "Card Emulation message");
byte[] aid = (byte[]) msg.obj;
/* Send broadcast ordered */
Intent TransactionIntent = new Intent();
TransactionIntent.setAction(NfcAdapter.ACTION_TRANSACTION_DETECTED);
TransactionIntent.putExtra(NfcAdapter.EXTRA_AID, aid);
if (DBG) Log.d(TAG, "Broadcasting Card Emulation event");
mContext.sendOrderedBroadcast(TransactionIntent, NFC_PERM);
break;
case MSG_LLCP_LINK_ACTIVATION:
NativeP2pDevice device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Activation message");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_TARGET");
if (device.doConnect()) {
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Initiator Activate LLCP OK");
activateLlcpLink();
} else {
/* should not happen */
Log.w(TAG, "Initiator Activate LLCP NOK. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Remote Target does not support LLCP. Disconnect.");
device.doDisconnect();
}
} else {
if (DBG) Log.d(TAG, "Cannot connect remote Target. Restart polling loop.");
device.doDisconnect();
}
} else if (device.getMode() == NativeP2pDevice.MODE_P2P_INITIATOR) {
if (DBG) Log.d(TAG, "NativeP2pDevice.MODE_P2P_INITIATOR");
/* Check Llcp compliancy */
if (mManager.doCheckLlcp()) {
/* Activate Llcp Link */
if (mManager.doActivateLlcp()) {
if (DBG) Log.d(TAG, "Target Activate LLCP OK");
activateLlcpLink();
}
} else {
Log.w(TAG, "checkLlcp failed");
}
}
break;
case MSG_LLCP_LINK_DEACTIVATED:
device = (NativeP2pDevice) msg.obj;
Log.d(TAG, "LLCP Link Deactivated message. Restart polling loop.");
if (device.getMode() == NativeP2pDevice.MODE_P2P_TARGET) {
if (DBG) Log.d(TAG, "disconnecting from target");
/* Restart polling loop */
device.doDisconnect();
} else {
if (DBG) Log.d(TAG, "not disconnecting from initiator");
}
/* Mark the link state */
mLlcpLinkState = NfcAdapter.LLCP_LINK_STATE_DEACTIVATED;
/* Broadcast Intent Link LLCP activated */
Intent LlcpLinkIntent = new Intent();
LlcpLinkIntent.setAction(NfcAdapter.ACTION_LLCP_LINK_STATE_CHANGED);
LlcpLinkIntent.putExtra(NfcAdapter.EXTRA_LLCP_LINK_STATE_CHANGED,
NfcAdapter.LLCP_LINK_STATE_DEACTIVATED);
if (DBG) Log.d(TAG, "Broadcasting LLCP deactivation");
mContext.sendOrderedBroadcast(LlcpLinkIntent, NFC_PERM);
break;
case MSG_TARGET_DESELECTED:
/* Broadcast Intent Target Deselected */
if (DBG) Log.d(TAG, "Target Deselected");
Intent TargetDeselectedIntent = new Intent();
TargetDeselectedIntent.setAction(mManager.INTERNAL_TARGET_DESELECTED_ACTION);
if (DBG) Log.d(TAG, "Broadcasting Intent");
mContext.sendOrderedBroadcast(TargetDeselectedIntent, NFC_PERM);
break;
case MSG_SHOW_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.setIcon("nfc", R.drawable.stat_sys_nfc, 0);
break;
}
case MSG_HIDE_MY_TAG_ICON: {
StatusBarManager sb = (StatusBarManager) getSystemService(
Context.STATUS_BAR_SERVICE);
sb.removeIcon("nfc");
break;
}
default:
Log.e(TAG, "Unknown message received");
break;
}
}
|
diff --git a/src/test/java/hudson/remoting/ChannelRunner.java b/src/test/java/hudson/remoting/ChannelRunner.java
index 1472b3c6..0be25f94 100644
--- a/src/test/java/hudson/remoting/ChannelRunner.java
+++ b/src/test/java/hudson/remoting/ChannelRunner.java
@@ -1,184 +1,184 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.remoting;
import hudson.remoting.Channel.Mode;
import junit.framework.Assert;
import java.io.IOException;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.net.URLClassLoader;
import java.net.URL;
import org.apache.commons.io.output.TeeOutputStream;
import org.apache.commons.io.FileUtils;
/**
* Hides the logic of starting/stopping a channel for test.
*
* @author Kohsuke Kawaguchi
*/
interface ChannelRunner {
Channel start() throws Exception;
void stop(Channel channel) throws Exception;
String getName();
/**
* Runs a channel in the same JVM.
*/
static class InProcess implements ChannelRunner {
private ExecutorService executor;
/**
* failure occurred in the other {@link Channel}.
*/
private Exception failure;
public Channel start() throws Exception {
final FastPipedInputStream in1 = new FastPipedInputStream();
final FastPipedOutputStream out1 = new FastPipedOutputStream(in1);
final FastPipedInputStream in2 = new FastPipedInputStream();
final FastPipedOutputStream out2 = new FastPipedOutputStream(in2);
executor = Executors.newCachedThreadPool();
Thread t = new Thread("south bridge runner") {
public void run() {
try {
- Channel s = new Channel("south", executor, Mode.BINARY, in2, out1, null, false, createCapability());
+ Channel s = new Channel("south", executor, Mode.BINARY, in2, out1, null, false, null, createCapability());
s.join();
System.out.println("south completed");
} catch (IOException e) {
e.printStackTrace();
failure = e;
} catch (InterruptedException e) {
e.printStackTrace();
failure = e;
}
}
};
t.start();
- return new Channel("north", executor, Mode.BINARY, in1, out2, null, false, createCapability());
+ return new Channel("north", executor, Mode.BINARY, in1, out2, null, false, null, createCapability());
}
public void stop(Channel channel) throws Exception {
channel.close();
System.out.println("north completed");
executor.shutdown();
if(failure!=null)
throw failure; // report a failure in the south side
}
public String getName() {
return "local";
}
protected Capability createCapability() {
return new Capability();
}
}
static class InProcessCompatibilityMode extends InProcess {
public String getName() {
return "local-compatibility";
}
@Override
protected Capability createCapability() {
return Capability.NONE;
}
}
/**
* Runs a channel in a separate JVM by launching a new JVM.
*/
static class Fork implements ChannelRunner {
private Process proc;
private ExecutorService executor;
private Copier copier;
public Channel start() throws Exception {
System.out.println("forking a new process");
// proc = Runtime.getRuntime().exec("java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8000 hudson.remoting.Launcher");
System.out.println(getClasspath());
proc = Runtime.getRuntime().exec(new String[]{"java","-cp",getClasspath(),"hudson.remoting.Launcher"});
copier = new Copier("copier",proc.getErrorStream(),System.out);
copier.start();
executor = Executors.newCachedThreadPool();
OutputStream out = proc.getOutputStream();
if (RECORD_OUTPUT) {
File f = File.createTempFile("remoting",".log");
System.out.println("Recording to "+f);
out = new TeeOutputStream(out,new FileOutputStream(f));
}
return new Channel("north", executor, proc.getInputStream(), out);
}
public void stop(Channel channel) throws Exception {
channel.close();
channel.join(10*1000);
// System.out.println("north completed");
executor.shutdown();
copier.join();
int r = proc.waitFor();
// System.out.println("south completed");
Assert.assertEquals("exit code should have been 0",0,r);
}
public String getName() {
return "fork";
}
public String getClasspath() {
// this assumes we run in Maven
StringBuilder buf = new StringBuilder();
URLClassLoader ucl = (URLClassLoader)getClass().getClassLoader();
for (URL url : ucl.getURLs()) {
if (buf.length()>0) buf.append(File.pathSeparatorChar);
buf.append(FileUtils.toFile(url)); // assume all of them are file URLs
}
return buf.toString();
}
/**
* Record the communication to the remote node. Used during debugging.
*/
private static boolean RECORD_OUTPUT = false;
}
}
| false | true | public Channel start() throws Exception {
final FastPipedInputStream in1 = new FastPipedInputStream();
final FastPipedOutputStream out1 = new FastPipedOutputStream(in1);
final FastPipedInputStream in2 = new FastPipedInputStream();
final FastPipedOutputStream out2 = new FastPipedOutputStream(in2);
executor = Executors.newCachedThreadPool();
Thread t = new Thread("south bridge runner") {
public void run() {
try {
Channel s = new Channel("south", executor, Mode.BINARY, in2, out1, null, false, createCapability());
s.join();
System.out.println("south completed");
} catch (IOException e) {
e.printStackTrace();
failure = e;
} catch (InterruptedException e) {
e.printStackTrace();
failure = e;
}
}
};
t.start();
return new Channel("north", executor, Mode.BINARY, in1, out2, null, false, createCapability());
}
| public Channel start() throws Exception {
final FastPipedInputStream in1 = new FastPipedInputStream();
final FastPipedOutputStream out1 = new FastPipedOutputStream(in1);
final FastPipedInputStream in2 = new FastPipedInputStream();
final FastPipedOutputStream out2 = new FastPipedOutputStream(in2);
executor = Executors.newCachedThreadPool();
Thread t = new Thread("south bridge runner") {
public void run() {
try {
Channel s = new Channel("south", executor, Mode.BINARY, in2, out1, null, false, null, createCapability());
s.join();
System.out.println("south completed");
} catch (IOException e) {
e.printStackTrace();
failure = e;
} catch (InterruptedException e) {
e.printStackTrace();
failure = e;
}
}
};
t.start();
return new Channel("north", executor, Mode.BINARY, in1, out2, null, false, null, createCapability());
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/RepositoryElementActionGroup.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/RepositoryElementActionGroup.java
index 46427a314..1ff2510ea 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/RepositoryElementActionGroup.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/actions/RepositoryElementActionGroup.java
@@ -1,373 +1,373 @@
/*******************************************************************************
* Copyright (c) 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.actions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.internal.tasks.core.TaskCategory;
import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction.Mode;
import org.eclipse.mylyn.internal.tasks.ui.views.Messages;
import org.eclipse.mylyn.internal.tasks.ui.views.UpdateRepositoryConfigurationAction;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskContainer;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
/**
* @author Steffen Pingel
*/
public class RepositoryElementActionGroup {
protected static final String ID_SEPARATOR_NEW = "new"; //$NON-NLS-1$
private static final String ID_SEPARATOR_OPERATIONS = "operations"; //$NON-NLS-1$
private static final String ID_SEPARATOR_TASKS = "tasks"; //$NON-NLS-1$
protected static final String ID_SEPARATOR_REPOSITORY = "repository"; //$NON-NLS-1$
private static final String ID_SEPARATOR_PROPERTIES = "properties"; //$NON-NLS-1$
protected static final String ID_SEPARATOR_NAVIGATE = "navigate"; //$NON-NLS-1$
private static final String ID_SEPARATOR_OPEN = "open"; //$NON-NLS-1$
protected static final String ID_SEPARATOR_EDIT = "edit"; //$NON-NLS-1$
private final CopyTaskDetailsAction copyUrlAction;
private final CopyTaskDetailsAction copyKeyAction;
private final CopyTaskDetailsAction copyDetailsAction;
private final OpenTaskListElementAction openAction;
private final OpenWithBrowserAction openWithBrowserAction;
private final DeleteAction deleteAction;
private final RemoveFromCategoryAction removeFromCategoryAction;
private final ShowInSearchViewAction showInSearchViewAction;
private final ShowInTaskListAction showInTaskListAction;
private final TaskActivateAction activateAction;
private final TaskDeactivateAction deactivateAction;
private ISelectionProvider selectionProvider;
private final List<ISelectionChangedListener> actions;
private final AutoUpdateQueryAction autoUpdateAction;
private final NewSubTaskAction newSubTaskAction;
public RepositoryElementActionGroup() {
actions = new ArrayList<ISelectionChangedListener>();
newSubTaskAction = add(new NewSubTaskAction());
activateAction = add(new TaskActivateAction());
deactivateAction = new TaskDeactivateAction();
copyKeyAction = add(new CopyTaskDetailsAction(Mode.KEY));
copyUrlAction = add(new CopyTaskDetailsAction(Mode.URL));
copyDetailsAction = add(new CopyTaskDetailsAction(Mode.SUMMARY_URL));
if (!isInEditor()) {
copyDetailsAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
}
removeFromCategoryAction = add(new RemoveFromCategoryAction());
deleteAction = add(new DeleteAction());
openAction = add(new OpenTaskListElementAction());
openWithBrowserAction = add(new OpenWithBrowserAction());
showInSearchViewAction = add(new ShowInSearchViewAction());
showInTaskListAction = add(new ShowInTaskListAction());
autoUpdateAction = add(new AutoUpdateQueryAction());
}
private <T extends ISelectionChangedListener> T add(T action) {
actions.add(action);
return action;
}
public void setSelectionProvider(ISelectionProvider selectionProvider) {
if (this.selectionProvider != null) {
for (ISelectionChangedListener action : actions) {
this.selectionProvider.removeSelectionChangedListener(action);
}
}
this.selectionProvider = selectionProvider;
if (selectionProvider != null) {
for (ISelectionChangedListener action : actions) {
this.selectionProvider.addSelectionChangedListener(action);
ISelection selection = selectionProvider.getSelection();
if (selection == null) {
selection = StructuredSelection.EMPTY;
}
action.selectionChanged(new SelectionChangedEvent(selectionProvider, selection));
}
}
}
public void fillContextMenu(final IMenuManager manager) {
manager.add(new Separator(ID_SEPARATOR_NEW)); // new, schedule
manager.add(new GroupMarker(ID_SEPARATOR_NAVIGATE)); // mark, go into, go up
manager.add(new Separator(ID_SEPARATOR_OPEN)); // open, activate
manager.add(new Separator(ID_SEPARATOR_EDIT)); // cut, copy paste, delete, rename
manager.add(new Separator(ID_SEPARATOR_TASKS)); // move to
+ manager.add(new GroupMarker(ID_SEPARATOR_OPERATIONS)); // repository properties, import/export, context
manager.add(new Separator(ID_SEPARATOR_REPOSITORY)); // synchronize
- manager.add(new Separator(ID_SEPARATOR_OPERATIONS)); // repository properties, import/export, context
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(new Separator(ID_SEPARATOR_PROPERTIES)); // properties
final ITaskContainer element;
IStructuredSelection selection = getSelection();
final Object firstSelectedObject = selection.getFirstElement();
if (firstSelectedObject instanceof ITaskContainer) {
element = (ITaskContainer) firstSelectedObject;
} else {
element = null;
}
final List<IRepositoryElement> selectedElements = getSelectedTaskContainers(selection);
AbstractTask task = null;
if (element instanceof ITask) {
task = (AbstractTask) element;
}
if (!isInTaskList() && newSubTaskAction.isEnabled()) {
MenuManager newSubMenu = new MenuManager("New");
newSubMenu.add(newSubTaskAction);
manager.appendToGroup(ID_SEPARATOR_NEW, newSubMenu);
}
if (element instanceof ITask && !isInEditor()) {
addAction(ID_SEPARATOR_OPEN, openAction, manager, element);
}
if (openWithBrowserAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, openWithBrowserAction);
}
showInSearchViewAction.selectionChanged(selection);
if (showInSearchViewAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInSearchViewAction);
}
showInTaskListAction.selectionChanged(selection);
if (showInTaskListAction.isEnabled() && !isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInTaskListAction);
}
if (task != null) {
if (task.isActive()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, deactivateAction);
} else {
manager.appendToGroup(ID_SEPARATOR_OPEN, activateAction);
}
}
if (!selection.isEmpty()) {
MenuManager copyDetailsSubMenu = new MenuManager(
Messages.RepositoryElementActionGroup_Copy_Detail_Menu_Label, CopyTaskDetailsAction.ID);
copyDetailsSubMenu.add(copyKeyAction);
copyDetailsSubMenu.add(copyUrlAction);
copyDetailsSubMenu.add(copyDetailsAction);
manager.appendToGroup(ID_SEPARATOR_EDIT, copyDetailsSubMenu);
}
if (isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, deleteAction);
}
removeFromCategoryAction.selectionChanged(selection);
removeFromCategoryAction.setEnabled(isRemoveFromCategoryEnabled(selectedElements));
if (removeFromCategoryAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, removeFromCategoryAction);
}
if (autoUpdateAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_REPOSITORY, autoUpdateAction);
}
if (element instanceof IRepositoryQuery) {
EditRepositoryPropertiesAction repositoryPropertiesAction = new EditRepositoryPropertiesAction();
repositoryPropertiesAction.selectionChanged(new StructuredSelection(element));
if (repositoryPropertiesAction.isEnabled()) {
MenuManager subMenu = new MenuManager(Messages.TaskListView_Repository);
manager.appendToGroup(ID_SEPARATOR_OPERATIONS, subMenu);
UpdateRepositoryConfigurationAction resetRepositoryConfigurationAction = new UpdateRepositoryConfigurationAction();
resetRepositoryConfigurationAction.selectionChanged(new StructuredSelection(element));
subMenu.add(resetRepositoryConfigurationAction);
subMenu.add(new Separator());
subMenu.add(repositoryPropertiesAction);
}
}
Map<String, List<IDynamicSubMenuContributor>> dynamicMenuMap = TasksUiPlugin.getDefault().getDynamicMenuMap();
for (final String menuPath : dynamicMenuMap.keySet()) {
for (final IDynamicSubMenuContributor contributor : dynamicMenuMap.get(menuPath)) {
SafeRunnable.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Menu contributor failed")); //$NON-NLS-1$
}
public void run() throws Exception {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
addMenuManager(menuPath, subMenuManager, manager, element);
}
}
});
}
}
}
private boolean isInTaskList() {
return (this instanceof TaskListViewActionGroup);
}
private IStructuredSelection getSelection() {
ISelection selection = (selectionProvider != null) ? selectionProvider.getSelection() : null;
if (selection instanceof IStructuredSelection) {
return (IStructuredSelection) selection;
}
return StructuredSelection.EMPTY;
}
private boolean isInEditor() {
return (this instanceof TaskEditorActionGroup);
}
private boolean isRemoveFromCategoryEnabled(final List<IRepositoryElement> selectedElements) {
if (selectedElements.isEmpty()) {
return false;
}
for (IRepositoryElement element : selectedElements) {
if (element instanceof AbstractTask) {
boolean hasCategory = false;
for (ITaskContainer container : ((AbstractTask) element).getParentContainers()) {
if (container instanceof TaskCategory) {
hasCategory = true;
}
}
if (!hasCategory) {
return false;
}
} else {
return false;
}
}
return true;
}
private void addMenuManager(String path, IMenuManager menuToAdd, IMenuManager manager, ITaskContainer element) {
if (element instanceof ITask || element instanceof IRepositoryQuery) {
manager.appendToGroup(path, menuToAdd);
}
}
private void addAction(String path, Action action, IMenuManager manager, ITaskContainer element) {
action.setEnabled(false);
if (element != null) {
updateActionEnablement(action, element);
}
manager.appendToGroup(path, action);
}
// TODO move the enablement to the action classes
private void updateActionEnablement(Action action, ITaskContainer element) {
if (element instanceof ITask) {
if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
action.setEnabled(true);
}
} else if (element != null) {
if (action instanceof GoIntoAction) {
TaskCategory cat = (TaskCategory) element;
if (cat.getChildren().size() > 0) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyTaskDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
if (element instanceof AbstractTaskCategory) {
AbstractTaskCategory container = (AbstractTaskCategory) element;
action.setEnabled(container.isUserManaged());
} else if (element instanceof IRepositoryQuery) {
action.setEnabled(true);
}
}
} else {
action.setEnabled(true);
}
}
public List<IRepositoryElement> getSelectedTaskContainers(IStructuredSelection selection) {
List<IRepositoryElement> selectedElements = new ArrayList<IRepositoryElement>();
for (Iterator<?> i = selection.iterator(); i.hasNext();) {
Object object = i.next();
if (object instanceof ITaskContainer) {
selectedElements.add((IRepositoryElement) object);
}
}
return selectedElements;
}
public OpenTaskListElementAction getOpenAction() {
return openAction;
}
public TaskActivateAction getActivateAction() {
return activateAction;
}
public DeleteAction getDeleteAction() {
return deleteAction;
}
public CopyTaskDetailsAction getCopyDetailsAction() {
return copyDetailsAction;
}
}
| false | true | public void fillContextMenu(final IMenuManager manager) {
manager.add(new Separator(ID_SEPARATOR_NEW)); // new, schedule
manager.add(new GroupMarker(ID_SEPARATOR_NAVIGATE)); // mark, go into, go up
manager.add(new Separator(ID_SEPARATOR_OPEN)); // open, activate
manager.add(new Separator(ID_SEPARATOR_EDIT)); // cut, copy paste, delete, rename
manager.add(new Separator(ID_SEPARATOR_TASKS)); // move to
manager.add(new Separator(ID_SEPARATOR_REPOSITORY)); // synchronize
manager.add(new Separator(ID_SEPARATOR_OPERATIONS)); // repository properties, import/export, context
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(new Separator(ID_SEPARATOR_PROPERTIES)); // properties
final ITaskContainer element;
IStructuredSelection selection = getSelection();
final Object firstSelectedObject = selection.getFirstElement();
if (firstSelectedObject instanceof ITaskContainer) {
element = (ITaskContainer) firstSelectedObject;
} else {
element = null;
}
final List<IRepositoryElement> selectedElements = getSelectedTaskContainers(selection);
AbstractTask task = null;
if (element instanceof ITask) {
task = (AbstractTask) element;
}
if (!isInTaskList() && newSubTaskAction.isEnabled()) {
MenuManager newSubMenu = new MenuManager("New");
newSubMenu.add(newSubTaskAction);
manager.appendToGroup(ID_SEPARATOR_NEW, newSubMenu);
}
if (element instanceof ITask && !isInEditor()) {
addAction(ID_SEPARATOR_OPEN, openAction, manager, element);
}
if (openWithBrowserAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, openWithBrowserAction);
}
showInSearchViewAction.selectionChanged(selection);
if (showInSearchViewAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInSearchViewAction);
}
showInTaskListAction.selectionChanged(selection);
if (showInTaskListAction.isEnabled() && !isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInTaskListAction);
}
if (task != null) {
if (task.isActive()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, deactivateAction);
} else {
manager.appendToGroup(ID_SEPARATOR_OPEN, activateAction);
}
}
if (!selection.isEmpty()) {
MenuManager copyDetailsSubMenu = new MenuManager(
Messages.RepositoryElementActionGroup_Copy_Detail_Menu_Label, CopyTaskDetailsAction.ID);
copyDetailsSubMenu.add(copyKeyAction);
copyDetailsSubMenu.add(copyUrlAction);
copyDetailsSubMenu.add(copyDetailsAction);
manager.appendToGroup(ID_SEPARATOR_EDIT, copyDetailsSubMenu);
}
if (isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, deleteAction);
}
removeFromCategoryAction.selectionChanged(selection);
removeFromCategoryAction.setEnabled(isRemoveFromCategoryEnabled(selectedElements));
if (removeFromCategoryAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, removeFromCategoryAction);
}
if (autoUpdateAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_REPOSITORY, autoUpdateAction);
}
if (element instanceof IRepositoryQuery) {
EditRepositoryPropertiesAction repositoryPropertiesAction = new EditRepositoryPropertiesAction();
repositoryPropertiesAction.selectionChanged(new StructuredSelection(element));
if (repositoryPropertiesAction.isEnabled()) {
MenuManager subMenu = new MenuManager(Messages.TaskListView_Repository);
manager.appendToGroup(ID_SEPARATOR_OPERATIONS, subMenu);
UpdateRepositoryConfigurationAction resetRepositoryConfigurationAction = new UpdateRepositoryConfigurationAction();
resetRepositoryConfigurationAction.selectionChanged(new StructuredSelection(element));
subMenu.add(resetRepositoryConfigurationAction);
subMenu.add(new Separator());
subMenu.add(repositoryPropertiesAction);
}
}
Map<String, List<IDynamicSubMenuContributor>> dynamicMenuMap = TasksUiPlugin.getDefault().getDynamicMenuMap();
for (final String menuPath : dynamicMenuMap.keySet()) {
for (final IDynamicSubMenuContributor contributor : dynamicMenuMap.get(menuPath)) {
SafeRunnable.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Menu contributor failed")); //$NON-NLS-1$
}
public void run() throws Exception {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
addMenuManager(menuPath, subMenuManager, manager, element);
}
}
});
}
}
}
| public void fillContextMenu(final IMenuManager manager) {
manager.add(new Separator(ID_SEPARATOR_NEW)); // new, schedule
manager.add(new GroupMarker(ID_SEPARATOR_NAVIGATE)); // mark, go into, go up
manager.add(new Separator(ID_SEPARATOR_OPEN)); // open, activate
manager.add(new Separator(ID_SEPARATOR_EDIT)); // cut, copy paste, delete, rename
manager.add(new Separator(ID_SEPARATOR_TASKS)); // move to
manager.add(new GroupMarker(ID_SEPARATOR_OPERATIONS)); // repository properties, import/export, context
manager.add(new Separator(ID_SEPARATOR_REPOSITORY)); // synchronize
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
manager.add(new Separator(ID_SEPARATOR_PROPERTIES)); // properties
final ITaskContainer element;
IStructuredSelection selection = getSelection();
final Object firstSelectedObject = selection.getFirstElement();
if (firstSelectedObject instanceof ITaskContainer) {
element = (ITaskContainer) firstSelectedObject;
} else {
element = null;
}
final List<IRepositoryElement> selectedElements = getSelectedTaskContainers(selection);
AbstractTask task = null;
if (element instanceof ITask) {
task = (AbstractTask) element;
}
if (!isInTaskList() && newSubTaskAction.isEnabled()) {
MenuManager newSubMenu = new MenuManager("New");
newSubMenu.add(newSubTaskAction);
manager.appendToGroup(ID_SEPARATOR_NEW, newSubMenu);
}
if (element instanceof ITask && !isInEditor()) {
addAction(ID_SEPARATOR_OPEN, openAction, manager, element);
}
if (openWithBrowserAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, openWithBrowserAction);
}
showInSearchViewAction.selectionChanged(selection);
if (showInSearchViewAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInSearchViewAction);
}
showInTaskListAction.selectionChanged(selection);
if (showInTaskListAction.isEnabled() && !isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, showInTaskListAction);
}
if (task != null) {
if (task.isActive()) {
manager.appendToGroup(ID_SEPARATOR_OPEN, deactivateAction);
} else {
manager.appendToGroup(ID_SEPARATOR_OPEN, activateAction);
}
}
if (!selection.isEmpty()) {
MenuManager copyDetailsSubMenu = new MenuManager(
Messages.RepositoryElementActionGroup_Copy_Detail_Menu_Label, CopyTaskDetailsAction.ID);
copyDetailsSubMenu.add(copyKeyAction);
copyDetailsSubMenu.add(copyUrlAction);
copyDetailsSubMenu.add(copyDetailsAction);
manager.appendToGroup(ID_SEPARATOR_EDIT, copyDetailsSubMenu);
}
if (isInTaskList()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, deleteAction);
}
removeFromCategoryAction.selectionChanged(selection);
removeFromCategoryAction.setEnabled(isRemoveFromCategoryEnabled(selectedElements));
if (removeFromCategoryAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_EDIT, removeFromCategoryAction);
}
if (autoUpdateAction.isEnabled()) {
manager.appendToGroup(ID_SEPARATOR_REPOSITORY, autoUpdateAction);
}
if (element instanceof IRepositoryQuery) {
EditRepositoryPropertiesAction repositoryPropertiesAction = new EditRepositoryPropertiesAction();
repositoryPropertiesAction.selectionChanged(new StructuredSelection(element));
if (repositoryPropertiesAction.isEnabled()) {
MenuManager subMenu = new MenuManager(Messages.TaskListView_Repository);
manager.appendToGroup(ID_SEPARATOR_OPERATIONS, subMenu);
UpdateRepositoryConfigurationAction resetRepositoryConfigurationAction = new UpdateRepositoryConfigurationAction();
resetRepositoryConfigurationAction.selectionChanged(new StructuredSelection(element));
subMenu.add(resetRepositoryConfigurationAction);
subMenu.add(new Separator());
subMenu.add(repositoryPropertiesAction);
}
}
Map<String, List<IDynamicSubMenuContributor>> dynamicMenuMap = TasksUiPlugin.getDefault().getDynamicMenuMap();
for (final String menuPath : dynamicMenuMap.keySet()) {
for (final IDynamicSubMenuContributor contributor : dynamicMenuMap.get(menuPath)) {
SafeRunnable.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Menu contributor failed")); //$NON-NLS-1$
}
public void run() throws Exception {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
addMenuManager(menuPath, subMenuManager, manager, element);
}
}
});
}
}
}
|
diff --git a/modules/org.restlet/src/org/restlet/data/Status.java b/modules/org.restlet/src/org/restlet/data/Status.java
index 237b1bdcc..ca7478dad 100644
--- a/modules/org.restlet/src/org/restlet/data/Status.java
+++ b/modules/org.restlet/src/org/restlet/data/Status.java
@@ -1,1521 +1,1521 @@
/*
* Copyright 2005-2007 Noelios Consulting.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License"). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* http://www.opensource.org/licenses/cddl1.txt See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at http://www.opensource.org/licenses/cddl1.txt If
* applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*/
package org.restlet.data;
/**
* Status to return after handling a call.
*
* @author Jerome Louvel ([email protected])
*/
public final class Status extends Metadata {
private static final String BASE_HTTP = "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html";
private static final String BASE_WEBDAV = "http://www.webdav.org/specs/rfc2518.html";
private static final String BASE_RESTLET = "http://www.restlet.org/docs/api/";
/**
* This interim response (the client has to wait for the final response) is
* used to inform the client that the initial part of the request has been
* received and has not yet been rejected or completed by the server.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1">HTTP
* RFC - 10.1.1 100 Continue</a>
*/
public static final Status INFO_CONTINUE = new Status(100);
/**
* The server understands and is willing to comply with the client's
* request, via the Upgrade message header field, for a change in the
* application protocol being used on this connection.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.2">HTTP
* RFC - 10.1.1 101 Switching Protocols</a>
*/
public static final Status INFO_SWITCHING_PROTOCOL = new Status(101);
/**
* This interim response is used to inform the client that the server has
* accepted the complete request, but has not yet completed it since the
* server has a reasonable expectation that the request will take
* significant time to complete.
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_102">WEBDAV
* RFC - 10.1 102 Processing</a>
*/
public static final Status INFO_PROCESSING = new Status(102);
/**
* The request has succeeded.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1">HTTP
* RFC - 10.2.1 200 OK</a>
*/
public static final Status SUCCESS_OK = new Status(200);
/**
* The request has been fulfilled and resulted in a new resource being
* created.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2">HTTP
* RFC - 10.2.2 201 Created</a>
*/
public static final Status SUCCESS_CREATED = new Status(201);
/**
* The request has been accepted for processing, but the processing has not
* been completed.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3">HTTP
* RFC - 10.2.3 202 Accepted</a>
*/
public static final Status SUCCESS_ACCEPTED = new Status(202);
/**
* The request has succeeded but the returned metainformation in the
* entity-header do not come from the origin server, but is gathered from a
* local or a third-party copy.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.4">HTTP
* RFC - 10.2.4 203 Non-Authoritative Information</a>
*/
public static final Status SUCCESS_NON_AUTHORITATIVE = new Status(203);
/**
* The server has fulfilled the request but does not need to return an
* entity-body (for example after a DELETE), and might want to return
* updated metainformation.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5">HTTP
* RFC - 10.2.5 204 No Content</a>
*/
public static final Status SUCCESS_NO_CONTENT = new Status(204);
/**
* The server has fulfilled the request and the user agent SHOULD reset the
* document view which caused the request to be sent.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6">HTTP
* RFC - 10.2.6 205 Reset Content</a>
*/
public static final Status SUCCESS_RESET_CONTENT = new Status(205);
/**
* The server has fulfilled the partial GET request for the resource
* assuming the request has included a Range header field indicating the
* desired range.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7">HTTP
* RFC - 10.2.7 206 Partial Content</a>
*/
public static final Status SUCCESS_PARTIAL_CONTENT = new Status(206);
/**
* This response is used to inform the client that the HTTP response entity
* contains a set of status codes generated during the method invocation.
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_207">WEBDAV
* RFC - 10.2 207 Multi-Status</a>
*/
public static final Status SUCCESS_MULTI_STATUS = new Status(207);
/**
* The server lets the user agent choosing one of the multiple
* representations of the requested resource, each representation having its
* own specific location provided in the response entity.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1">HTTP
* RFC - 10.3.1 300 Multiple Choices</a>
*/
public static final Status REDIRECTION_MULTIPLE_CHOICES = new Status(300);
/**
* The requested resource has been assigned a new permanent URI and any
* future references to this resource SHOULD use one of the returned URIs.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2">HTTP
* RFC - 10.3.2 301 Moved Permanently</a>
*/
public static final Status REDIRECTION_PERMANENT = new Status(301);
/**
* The requested resource resides temporarily under a different URI which
* should not be used for future requests by the client (use status codes
* 303 or 307 instead since this status has been manifestly misused).
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3">HTTP
* RFC - 10.3.3 302 Found</a>
*/
public static final Status REDIRECTION_FOUND = new Status(302);
/**
* The response to the request can be found under a different URI and SHOULD
* be retrieved using a GET method on that resource.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4">HTTP
* RFC - 10.3.4 303 See Other</a>
*/
public static final Status REDIRECTION_SEE_OTHER = new Status(303);
/**
* Status code sent by the server in response to a conditional GET request
* in case the document has not been modified.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5">HTTP
* RFC - 10.3.5 304 Not Modified</a>
*/
public static final Status REDIRECTION_NOT_MODIFIED = new Status(304);
/**
* The requested resource MUST be accessed through the proxy given by the
* Location field.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.6">HTTP
* RFC - 10.3.6 305 Use Proxy</a>
*/
public static final Status REDIRECTION_USE_PROXY = new Status(305);
/**
* The requested resource resides temporarily under a different URI which
* should not be used for future requests by the client.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8">HTTP
* RFC - 10.3.8 307 Temporary Redirect</a>
*/
public static final Status REDIRECTION_TEMPORARY = new Status(307);
/**
* The request could not be understood by the server due to malformed
* syntax.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1">HTTP
* RFC - 10.4.1 400 Bad Request</a>
*/
public static final Status CLIENT_ERROR_BAD_REQUEST = new Status(400);
/**
* The request requires user authentication.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2">HTTP
* RFC - 10.4.2 401 Unauthorized</a>
*/
public static final Status CLIENT_ERROR_UNAUTHORIZED = new Status(401);
/**
* This code is reserved for future use.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.3">HTTP
* RFC - 10.4.3 402 Payment Required</a>
*/
public static final Status CLIENT_ERROR_PAYMENT_REQUIRED = new Status(402);
/**
* The server understood the request, but is refusing to fulfill it as it
* could be explained in the entity.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4">HTTP
* RFC - 10.4.4 403 Forbidden</a>
*/
public static final Status CLIENT_ERROR_FORBIDDEN = new Status(403);
/**
* The server has not found anything matching the Request-URI or the server
* does not wish to reveal exactly why the request has been refused, or no
* other response is applicable.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5">HTTP
* RFC - 10.4.5 404 Not Found</a>
*/
public static final Status CLIENT_ERROR_NOT_FOUND = new Status(404);
/**
* The method specified in the Request-Line is not allowed for the resource
* identified by the Request-URI.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6">HTTP
* RFC - 10.4.6 405 Method Not Allowed</a>
*/
public static final Status CLIENT_ERROR_METHOD_NOT_ALLOWED = new Status(405);
/**
* The resource identified by the request is only capable of generating
* response entities whose content characteristics do not match the user's
* requirements (in Accept* headers).
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7">HTTP
* RFC - 10.4.7 406 Not Acceptable</a>
*/
public static final Status CLIENT_ERROR_NOT_ACCEPTABLE = new Status(406);
/**
* This code is similar to 401 (Unauthorized), but indicates that the client
* must first authenticate itself with the proxy.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8">HTTP
* RFC - 10.4.8 407 Proxy Authentication Required</a>
*/
public static final Status CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED = new Status(
407);
/**
* Sent by the server when an HTTP client opens a connection, but has never
* sent a request (or never sent the blank line that signals the end of the
* request).
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9">HTTP
* RFC - 10.4.9 408 Request Timeout</a>
*/
public static final Status CLIENT_ERROR_REQUEST_TIMEOUT = new Status(408);
/**
* The request could not be completed due to a conflict with the current
* state of the resource (as experienced in a version control system).
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10">HTTP
* RFC - 10.4.10 409 Conflict</a>
*/
public static final Status CLIENT_ERROR_CONFLICT = new Status(409);
/**
* The requested resource is no longer available at the server and no
* forwarding address is known.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11">HTTP
* RFC - 10.4.11 410 Gone</a>
*/
public static final Status CLIENT_ERROR_GONE = new Status(410);
/**
* The server refuses to accept the request without a defined
* Content-Length.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.12">HTTP
* RFC - 10.4.12 411 Length Required</a>
*/
public static final Status CLIENT_ERROR_LENGTH_REQUIRED = new Status(411);
/**
* Sent by the server when the user agent asks the server to carry out a
* request under certain conditions that are not met.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.13">HTTP
* RFC - 10.4.13 412 Precondition Failed</a>
*/
public static final Status CLIENT_ERROR_PRECONDITION_FAILED = new Status(
412);
/**
* The server is refusing to process a request because the request entity is
* larger than the server is willing or able to process.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.14">HTTP
* RFC - 10.4.14 413 Request Entity Too Large</a>
*/
public static final Status CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE = new Status(
413);
/**
* The server is refusing to service the request because the Request-URI is
* longer than the server is willing to interpret.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15">HTTP
* RFC - 10.4.15 414 Request-URI Too Long</a>
*/
public static final Status CLIENT_ERROR_REQUEST_URI_TOO_LONG = new Status(
414);
/**
* The server is refusing to service the request because the entity of the
* request is in a format not supported by the requested resource for the
* requested method.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16">HTTP
* RFC - 10.4.16 415 Unsupported Media Type</a>
*/
public static final Status CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE = new Status(
415);
/**
* The request includes a Range request-header field and the selected
* resource is too small for any of the byte-ranges to apply.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17">HTTP
* RFC - 10.4.17 416 Requested Range Not Satisfiable</a>
*/
public static final Status CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE = new Status(
416);
/**
* The user agent expects some behaviour of the server (given in an Expect
* request-header field), but this expectation could not be met by this
* server.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.18">HTTP
* RFC - 10.4.18 417 Expectation Failed</a>
*/
public static final Status CLIENT_ERROR_EXPECTATION_FAILED = new Status(417);
/**
* This status code means the server understands the content type of the
* request entity (syntactically correct) but was unable to process the
* contained instructions.
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_422">WEBDAV
* RFC - 10.3 422 Unprocessable Entity</a>
*/
public static final Status CLIENT_ERROR_UNPROCESSABLE_ENTITY = new Status(
422);
/**
* The source or destination resource of a method is locked (or temporarily
* involved in another process).
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_423">WEBDAV
* RFC - 10.4 423 Locked</a>
*/
public static final Status CLIENT_ERROR_LOCKED = new Status(423);
/**
* This status code means that the method could not be performed on the
* resource because the requested action depended on another action and that
* action failed.
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_424">WEBDAV
* RFC - 10.5 424 Failed Dependency</a>
*/
public static final Status CLIENT_ERROR_FAILED_DEPENDENCY = new Status(424);
/**
* The server encountered an unexpected condition which prevented it from
* fulfilling the request.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1">HTTP
* RFC - 10.5.1 500 Internal Server Error</a>
*/
public static final Status SERVER_ERROR_INTERNAL = new Status(500);
/**
* The server does not support the functionality required to fulfill the
* request.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2">HTTP
* RFC - 10.5.2 501 Not Implemented</a>
*/
public static final Status SERVER_ERROR_NOT_IMPLEMENTED = new Status(501);
/**
* The server, while acting as a gateway or proxy, received an invalid
* response from the upstream server it accessed in attempting to fulfill
* the request.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3">HTTP
* RFC - 10.5.3 502 Bad Gateway</a>
*/
public static final Status SERVER_ERROR_BAD_GATEWAY = new Status(502);
/**
* The server is currently unable to handle the request due to a temporary
* overloading or maintenance of the server.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4">HTTP
* RFC - 10.5.4 503 Service Unavailable</a>
*/
public static final Status SERVER_ERROR_SERVICE_UNAVAILABLE = new Status(
503);
/**
* The server, while acting as a gateway or proxy, could not connect to the
* upstream server.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5">HTTP
* RFC - 10.5.5 504 Gateway Timeout</a>
*/
public static final Status SERVER_ERROR_GATEWAY_TIMEOUT = new Status(504);
/**
* The server does not support, or refuses to support, the HTTP protocol
* version that was used in the request message.
*
* @see <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.6">HTTP
* RFC - 10.5.6 505 HTTP Version Not Supported</a>
*/
public static final Status SERVER_ERROR_VERSION_NOT_SUPPORTED = new Status(
505);
/**
* This status code means the method could not be performed on the resource
* because the server is unable to store the representation needed to
* successfully complete the request.
*
* @see <a href="http://www.webdav.org/specs/rfc2518.html#STATUS_507">WEBDAV
* RFC - 10.6 507 Insufficient Storage</a>
*/
public static final Status SERVER_ERROR_INSUFFICIENT_STORAGE = new Status(
507);
/**
* A client connector can not connect to the remote server.
*/
public static final Status CONNECTOR_ERROR_CONNECTION = new Status(1000);
/**
* A client connector faces an error during the communication with the
* remote server (interruption, timeout, etc).
*/
public static final Status CONNECTOR_ERROR_COMMUNICATION = new Status(1001);
/**
* Generic status code sent by a client connector when an error occurs
* during the process of a request to its server or the process of a
* response to its client.
*/
public static final Status CONNECTOR_ERROR_INTERNAL = new Status(1002);
/**
* Indicates if the status is a client error status.
*
* @param code
* The code of the status.
* @return True if the status is a client error status.
*/
public static boolean isClientError(int code) {
boolean result = false;
switch (code) {
case 400:
case 401:
case 402:
case 403:
case 404:
case 405:
case 406:
case 407:
case 408:
case 409:
case 410:
case 411:
case 412:
case 413:
case 414:
case 415:
case 416:
case 417:
case 422:
case 423:
case 424:
result = true;
break;
}
return result;
}
/**
* Indicates if the status is a connector error status.
*
* @param code
* The code of the status.
* @return True if the status is a server error status.
*/
public static boolean isConnectorError(int code) {
boolean result = false;
switch (code) {
case 1000:
case 1001:
case 1002:
result = true;
break;
}
return result;
}
/**
* Indicates if the status is an error (client or server) status.
*
* @param code
* The code of the status.
* @return True if the status is an error (client or server) status.
*/
public static boolean isError(int code) {
return isClientError(code) || isServerError(code)
|| isConnectorError(code);
}
/**
* Indicates if the status is an information status.
*
* @param code
* The code of the status.
* @return True if the status is an information status.
*/
public static boolean isInfo(int code) {
boolean result = false;
switch (code) {
case 100:
case 101:
case 102:
result = true;
break;
}
return result;
}
/**
* Indicates if the status is a redirection status.
*
* @param code
* The code of the status.
* @return True if the status is a redirection status.
*/
public static boolean isRedirection(int code) {
boolean result = false;
switch (code) {
case 300:
case 301:
case 302:
case 303:
case 304:
case 305:
case 307:
result = true;
break;
}
return result;
}
/**
* Indicates if the status is a server error status.
*
* @param code
* The code of the status.
* @return True if the status is a server error status.
*/
public static boolean isServerError(int code) {
boolean result = false;
switch (code) {
case 500:
case 501:
case 502:
case 503:
case 504:
case 505:
case 507:
result = true;
break;
}
return result;
}
/**
* Indicates if the status is a success status.
*
* @param code
* The code of the status.
* @return True if the status is a success status.
*/
public static boolean isSuccess(int code) {
boolean result = false;
switch (code) {
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
case 206:
case 207:
result = true;
break;
}
return result;
}
/**
* Returns the status associated to a code. If an existing constant exists
* then it is returned, otherwise a new instance is created.
*
* @param code
* The code.
* @return The associated status.
*/
public static Status valueOf(int code) {
Status result = null;
switch (code) {
case 100:
result = INFO_CONTINUE;
break;
case 101:
result = INFO_SWITCHING_PROTOCOL;
break;
case 102:
result = INFO_PROCESSING;
break;
case 200:
result = SUCCESS_OK;
break;
case 201:
result = SUCCESS_CREATED;
break;
case 202:
result = SUCCESS_ACCEPTED;
break;
case 203:
result = SUCCESS_NON_AUTHORITATIVE;
break;
case 204:
result = SUCCESS_NO_CONTENT;
break;
case 205:
result = SUCCESS_RESET_CONTENT;
break;
case 206:
result = SUCCESS_PARTIAL_CONTENT;
break;
case 207:
result = SUCCESS_MULTI_STATUS;
break;
case 300:
result = REDIRECTION_MULTIPLE_CHOICES;
break;
case 301:
result = REDIRECTION_PERMANENT;
break;
case 302:
result = REDIRECTION_FOUND;
break;
case 303:
result = REDIRECTION_SEE_OTHER;
break;
case 304:
result = REDIRECTION_NOT_MODIFIED;
break;
case 305:
result = REDIRECTION_USE_PROXY;
break;
case 307:
result = REDIRECTION_TEMPORARY;
break;
case 400:
result = CLIENT_ERROR_BAD_REQUEST;
break;
case 401:
result = CLIENT_ERROR_UNAUTHORIZED;
break;
case 402:
result = CLIENT_ERROR_PAYMENT_REQUIRED;
break;
case 403:
result = CLIENT_ERROR_FORBIDDEN;
break;
case 404:
result = CLIENT_ERROR_NOT_FOUND;
break;
case 405:
result = CLIENT_ERROR_METHOD_NOT_ALLOWED;
break;
case 406:
result = CLIENT_ERROR_NOT_ACCEPTABLE;
break;
case 407:
result = CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED;
break;
case 408:
result = CLIENT_ERROR_REQUEST_TIMEOUT;
break;
case 409:
result = CLIENT_ERROR_CONFLICT;
break;
case 410:
result = CLIENT_ERROR_GONE;
break;
case 411:
result = CLIENT_ERROR_LENGTH_REQUIRED;
break;
case 412:
result = CLIENT_ERROR_PRECONDITION_FAILED;
break;
case 413:
result = CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE;
break;
case 414:
result = CLIENT_ERROR_REQUEST_URI_TOO_LONG;
break;
case 415:
result = CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE;
break;
case 416:
result = CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE;
break;
case 417:
result = CLIENT_ERROR_EXPECTATION_FAILED;
break;
case 422:
result = CLIENT_ERROR_UNPROCESSABLE_ENTITY;
break;
case 423:
result = CLIENT_ERROR_LOCKED;
break;
case 424:
result = CLIENT_ERROR_FAILED_DEPENDENCY;
break;
case 500:
result = SERVER_ERROR_INTERNAL;
break;
case 501:
result = SERVER_ERROR_NOT_IMPLEMENTED;
break;
case 502:
result = SERVER_ERROR_BAD_GATEWAY;
break;
case 503:
result = SERVER_ERROR_SERVICE_UNAVAILABLE;
break;
case 504:
result = SERVER_ERROR_GATEWAY_TIMEOUT;
break;
case 505:
result = SERVER_ERROR_VERSION_NOT_SUPPORTED;
break;
case 507:
result = SERVER_ERROR_INSUFFICIENT_STORAGE;
break;
case 1000:
result = CONNECTOR_ERROR_CONNECTION;
break;
case 1001:
result = CONNECTOR_ERROR_COMMUNICATION;
break;
case 1002:
result = CONNECTOR_ERROR_INTERNAL;
break;
}
return result;
}
/** The specification code. */
private int code;
/** The URI of the specification describing the method. */
private String uri;
/**
* Constructor.
*
* @param code
* The specification code.
*/
public Status(int code) {
this(code, null, null, null);
}
/**
* Constructor.
*
* @param code
* The specification code.
* @param name
* The name.
* @param description
* The description.
* @param uri
* The URI of the specification describing the method.
*/
public Status(int code, final String name, final String description,
final String uri) {
super(name, description);
this.code = code;
this.uri = uri;
}
/**
* Constructor.
*
* @param status
* The status to copy.
* @param description
* The description to associate.
*/
public Status(final Status status, final String description) {
this(status.getCode(), status.getName(), description, status.getUri());
}
/**
* Indicates if the status is equal to a given one.
*
* @param object
* The object to compare to.
* @return True if the status is equal to a given one.
*/
@Override
public boolean equals(final Object object) {
return (object instanceof Status)
&& (this.code == ((Status) object).getCode());
}
/**
* Returns the corresponding code (HTTP or WebDAV or custom code).
*
* @return The corresponding code.
*/
public int getCode() {
return this.code;
}
/**
* Returns the description.
*
* @return The description.
*/
public String getDescription() {
String result = super.getDescription();
if (result == null) {
switch (this.code) {
case 100:
result = "The client should continue with its request";
break;
case 101:
result = "The server is willing to change the application protocol being used on this connection";
break;
case 102:
result = "Interim response used to inform the client that the server has accepted the complete request, but has not yet completed it";
break;
case 200:
result = "The request has succeeded";
break;
case 201:
result = "The request has been fulfilled and resulted in a new resource being created";
break;
case 202:
result = "The request has been accepted for processing, but the processing has not been completed";
break;
case 203:
result = "The returned metainformation is not the definitive set as available from the origin server";
break;
case 204:
result = "The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation";
break;
case 205:
result = "The server has fulfilled the request and the user agent should reset the document view which caused the request to be sent";
break;
case 206:
result = "The server has fulfilled the partial get request for the resource";
break;
case 207:
result = "Provides status for multiple independent operations";
break;
case 300:
result = "The requested resource corresponds to any one of a set of representations";
break;
case 301:
result = "The requested resource has been assigned a new permanent URI";
break;
case 302:
result = "The requested resource can be found under a different URI";
break;
case 303:
result = "The response to the request can be found under a different URI";
break;
case 304:
result = "The client has performed a conditional GET request and the document has not been modified";
break;
case 305:
result = "The requested resource must be accessed through the proxy given by the location field";
break;
case 307:
result = "The requested resource resides temporarily under a different URI";
break;
case 400:
result = "The request could not be understood by the server due to malformed syntax";
break;
case 401:
result = "The request requires user authentication";
break;
case 402:
result = "This code is reserved for future use";
break;
case 403:
result = "The server understood the request, but is refusing to fulfill it";
break;
case 404:
result = "The server has not found anything matching the request URI";
break;
case 405:
result = "The method specified in the request is not allowed for the resource identified by the request URI";
break;
case 406:
result = "The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request";
break;
case 407:
result = "This code is similar to Unauthorized, but indicates that the client must first authenticate itself with the proxy";
break;
case 408:
result = "The client did not produce a request within the time that the server was prepared to wait";
break;
case 409:
result = "The request could not be completed due to a conflict with the current state of the resource";
break;
case 410:
result = "The requested resource is no longer available at the server and no forwarding address is known";
break;
case 411:
result = "The server refuses to accept the request without a defined content length";
break;
case 412:
result = "The precondition given in one or more of the request header fields evaluated to false when it was tested on the server";
break;
case 413:
result = "The server is refusing to process a request because the request entity is larger than the server is willing or able to process";
break;
case 414:
result = "The server is refusing to service the request because the request URI is longer than the server is willing to interpret";
break;
case 415:
result = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method";
break;
case 416:
result = "For byte ranges, this means that the first byte position were greater than the current length of the selected resource";
break;
case 417:
result = "The expectation given in the request header could not be met by this server";
break;
case 422:
result = "The server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the contained instructions";
break;
case 423:
result = "The source or destination resource of a method is locked";
break;
case 424:
result = "The method could not be performed on the resource because the requested action depended on another action and that action failed";
break;
case 500:
result = "The server encountered an unexpected condition which prevented it from fulfilling the request";
break;
case 501:
result = "The server does not support the functionality required to fulfill the request";
break;
case 502:
result = "The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request";
break;
case 503:
result = "The server is currently unable to handle the request due to a temporary overloading or maintenance of the server";
break;
case 504:
result = "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request";
break;
case 505:
result = "The server does not support, or refuses to support, the protocol version that was used in the request message";
break;
case 507:
result = "The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request";
break;
case 1000:
result = "The connector failed to connect to the server";
break;
case 1001:
result = "The connector failed to complete the communication with the server";
break;
case 1002:
result = "The connector encountered an unexpected condition which prevented it from fulfilling the request";
break;
}
}
return result;
}
/**
* Returns the name of this status.
*
* @return The name of this status.
*/
public String getName() {
String result = super.getName();
if (result == null) {
switch (this.code) {
case 100:
result = "Continue";
break;
case 101:
result = "Switching Protocols";
break;
case 102:
result = "Processing";
break;
case 200:
result = "OK";
break;
case 201:
result = "Created";
break;
case 202:
result = "Accepted";
break;
case 203:
result = "Non-Authoritative Information";
break;
case 204:
result = "No Content";
break;
case 205:
result = "Reset Content";
break;
case 206:
result = "Partial Content";
break;
case 207:
result = "Multi-Status";
break;
case 300:
result = "Multiple Choices";
break;
case 301:
result = "Moved Permanently";
break;
case 302:
result = "Found";
break;
case 303:
result = "See Other";
break;
case 304:
result = "Not Modified";
break;
case 305:
result = "Use Proxy";
break;
case 307:
result = "Temporary Redirect";
break;
case 400:
result = "Bad Request";
break;
case 401:
result = "Unauthorized";
break;
case 402:
result = "Payment Required";
break;
case 403:
result = "Forbidden";
break;
case 404:
result = "Not Found";
break;
case 405:
result = "Method Not Allowed";
break;
case 406:
result = "Not Acceptable";
break;
case 407:
result = "Proxy Authentication Required";
break;
case 408:
result = "Request Timeout";
break;
case 409:
result = "Conflict";
break;
case 410:
result = "Gone";
break;
case 411:
result = "Length Required";
break;
case 412:
result = "Precondition Failed";
break;
case 413:
result = "Request Entity Too Large";
break;
case 414:
result = "Request URI Too Long";
break;
case 415:
result = "Unsupported Media Type";
break;
case 416:
result = "Requested Range Not Satisfiable";
break;
case 417:
result = "Expectation Failed";
break;
case 422:
result = "Unprocessable Entity";
break;
case 423:
result = "Locked";
break;
case 424:
result = "Failed Dependency";
break;
case 500:
result = "Internal Server Error";
break;
case 501:
result = "Not Implemented";
break;
case 502:
result = "Bad Gateway";
break;
case 503:
result = "Service Unavailable";
break;
case 504:
result = "Gateway Timeout";
break;
case 505:
result = "Version Not Supported";
break;
case 507:
result = "Insufficient Storage";
break;
case 1000:
result = "Connection Error";
break;
case 1001:
result = "Communication Error";
break;
case 1002:
result = "Internal Connector Error";
break;
}
}
return result;
}
/**
* Returns the URI of the specification describing the status.
*
* @return The URI of the specification describing the status.
*/
public String getUri() {
String result = this.uri;
if (result == null) {
switch (this.code) {
case 100:
result = BASE_HTTP + "#sec10.1.1";
break;
case 101:
result = BASE_HTTP + "#sec10.1.2";
break;
case 102:
result = BASE_WEBDAV + "#STATUS_102";
break;
case 200:
result = BASE_HTTP + "#sec10.2.1";
break;
case 201:
result = BASE_HTTP + "#sec10.2.2";
break;
case 202:
result = BASE_HTTP + "#sec10.2.3";
break;
case 203:
result = BASE_HTTP + "#sec10.2.4";
break;
case 204:
result = BASE_HTTP + "#sec10.2.5";
break;
case 205:
result = BASE_HTTP + "#sec10.2.6";
break;
case 206:
result = BASE_HTTP + "#sec10.2.7";
break;
case 207:
result = BASE_WEBDAV + "#STATUS_207";
break;
case 300:
result = BASE_HTTP + "#sec10.3.1";
break;
case 301:
result = BASE_HTTP + "#sec10.3.2";
break;
case 302:
result = BASE_HTTP + "#sec10.3.3";
break;
case 303:
result = BASE_HTTP + "#sec10.3.4";
break;
case 304:
result = BASE_HTTP + "#sec10.3.5";
break;
case 305:
result = BASE_HTTP + "#sec10.3.6";
break;
case 307:
result = BASE_HTTP + "#sec10.3.8";
break;
case 400:
result = BASE_HTTP + "#sec10.4.1";
break;
case 401:
result = BASE_HTTP + "#sec10.4.2";
break;
case 402:
result = BASE_HTTP + "#sec10.4.3";
break;
case 403:
result = BASE_HTTP + "#sec10.4.4";
break;
case 404:
result = BASE_HTTP + "#sec10.4.5";
break;
case 405:
result = BASE_HTTP + "#sec10.4.6";
break;
case 406:
result = BASE_HTTP + "#sec10.4.7";
break;
case 407:
result = BASE_HTTP + "#sec10.4.8";
break;
case 408:
result = BASE_HTTP + "#sec10.4.9";
break;
case 409:
result = BASE_HTTP + "#sec10.4.10";
break;
case 410:
result = BASE_HTTP + "#sec10.4.11";
break;
case 411:
result = BASE_HTTP + "#sec10.4.12";
break;
case 412:
result = BASE_HTTP + "#sec10.4.13";
break;
case 413:
result = BASE_HTTP + "#sec10.4.14";
break;
case 414:
result = BASE_HTTP + "#sec10.4.15";
break;
case 415:
result = BASE_HTTP + "#sec10.4.16";
break;
case 416:
result = BASE_HTTP + "#sec10.4.17";
break;
case 417:
result = BASE_HTTP + "#sec10.4.18";
break;
case 422:
result = BASE_WEBDAV + "#STATUS_422";
break;
case 423:
result = BASE_WEBDAV + "#STATUS_423";
break;
case 424:
result = BASE_WEBDAV + "#STATUS_424";
break;
case 500:
result = BASE_HTTP + "#sec10.5.1";
break;
case 501:
result = BASE_HTTP + "#sec10.5.2";
break;
case 502:
result = BASE_HTTP + "#sec10.5.3";
break;
case 503:
result = BASE_HTTP + "#sec10.5.4";
break;
case 504:
result = BASE_HTTP + "#sec10.5.5";
break;
case 505:
result = BASE_HTTP + "#sec10.5.6";
break;
case 507:
result = BASE_WEBDAV + "#STATUS_507";
break;
case 1000:
result = BASE_RESTLET
- + "org/restlet/data/Statuses.html#CONNECTOR_ERROR_CONNECTION";
+ + "org/restlet/data/Status.html#CONNECTOR_ERROR_CONNECTION";
break;
case 1001:
result = BASE_RESTLET
- + "org/restlet/data/Statuses.html#CONNECTOR_ERROR_COMMUNICATION";
+ + "org/restlet/data/Status.html#CONNECTOR_ERROR_COMMUNICATION";
break;
case 1002:
result = BASE_RESTLET
- + "org/restlet/data/Statuses.html#CONNECTOR_ERROR_INTERNAL";
+ + "org/restlet/data/Status.html#CONNECTOR_ERROR_INTERNAL";
break;
}
}
return result;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return getCode();
}
/**
* Indicates if the status is a client error status.
*
* @return True if the status is a client error status.
*/
public boolean isClientError() {
return isClientError(getCode());
}
/**
* Indicates if the status is a connector error status.
*
* @return True if the status is a connector error status.
*/
public boolean isConnectorError() {
return isConnectorError(getCode());
}
/**
* Indicates if the status is an error (client or server) status.
*
* @return True if the status is an error (client or server) status.
*/
public boolean isError() {
return isError(getCode());
}
/**
* Indicates if the status is an information status.
*
* @return True if the status is an information status.
*/
public boolean isInfo() {
return isInfo(getCode());
}
/**
* Indicates if the status is a redirection status.
*
* @return True if the status is a redirection status.
*/
public boolean isRedirection() {
return isRedirection(getCode());
}
/**
* Indicates if the status is a server error status.
*
* @return True if the status is a server error status.
*/
public boolean isServerError() {
return isServerError(getCode());
}
/**
* Indicates if the status is a success status.
*
* @return True if the status is a success status.
*/
public boolean isSuccess() {
return isSuccess(getCode());
}
/**
* Returns the name of the status followed by its HTTP code.
*
* @return The name of the status followed by its HTTP code.
*/
public String toString() {
return getName() + " (" + this.code + ")";
}
}
| false | true | public String getUri() {
String result = this.uri;
if (result == null) {
switch (this.code) {
case 100:
result = BASE_HTTP + "#sec10.1.1";
break;
case 101:
result = BASE_HTTP + "#sec10.1.2";
break;
case 102:
result = BASE_WEBDAV + "#STATUS_102";
break;
case 200:
result = BASE_HTTP + "#sec10.2.1";
break;
case 201:
result = BASE_HTTP + "#sec10.2.2";
break;
case 202:
result = BASE_HTTP + "#sec10.2.3";
break;
case 203:
result = BASE_HTTP + "#sec10.2.4";
break;
case 204:
result = BASE_HTTP + "#sec10.2.5";
break;
case 205:
result = BASE_HTTP + "#sec10.2.6";
break;
case 206:
result = BASE_HTTP + "#sec10.2.7";
break;
case 207:
result = BASE_WEBDAV + "#STATUS_207";
break;
case 300:
result = BASE_HTTP + "#sec10.3.1";
break;
case 301:
result = BASE_HTTP + "#sec10.3.2";
break;
case 302:
result = BASE_HTTP + "#sec10.3.3";
break;
case 303:
result = BASE_HTTP + "#sec10.3.4";
break;
case 304:
result = BASE_HTTP + "#sec10.3.5";
break;
case 305:
result = BASE_HTTP + "#sec10.3.6";
break;
case 307:
result = BASE_HTTP + "#sec10.3.8";
break;
case 400:
result = BASE_HTTP + "#sec10.4.1";
break;
case 401:
result = BASE_HTTP + "#sec10.4.2";
break;
case 402:
result = BASE_HTTP + "#sec10.4.3";
break;
case 403:
result = BASE_HTTP + "#sec10.4.4";
break;
case 404:
result = BASE_HTTP + "#sec10.4.5";
break;
case 405:
result = BASE_HTTP + "#sec10.4.6";
break;
case 406:
result = BASE_HTTP + "#sec10.4.7";
break;
case 407:
result = BASE_HTTP + "#sec10.4.8";
break;
case 408:
result = BASE_HTTP + "#sec10.4.9";
break;
case 409:
result = BASE_HTTP + "#sec10.4.10";
break;
case 410:
result = BASE_HTTP + "#sec10.4.11";
break;
case 411:
result = BASE_HTTP + "#sec10.4.12";
break;
case 412:
result = BASE_HTTP + "#sec10.4.13";
break;
case 413:
result = BASE_HTTP + "#sec10.4.14";
break;
case 414:
result = BASE_HTTP + "#sec10.4.15";
break;
case 415:
result = BASE_HTTP + "#sec10.4.16";
break;
case 416:
result = BASE_HTTP + "#sec10.4.17";
break;
case 417:
result = BASE_HTTP + "#sec10.4.18";
break;
case 422:
result = BASE_WEBDAV + "#STATUS_422";
break;
case 423:
result = BASE_WEBDAV + "#STATUS_423";
break;
case 424:
result = BASE_WEBDAV + "#STATUS_424";
break;
case 500:
result = BASE_HTTP + "#sec10.5.1";
break;
case 501:
result = BASE_HTTP + "#sec10.5.2";
break;
case 502:
result = BASE_HTTP + "#sec10.5.3";
break;
case 503:
result = BASE_HTTP + "#sec10.5.4";
break;
case 504:
result = BASE_HTTP + "#sec10.5.5";
break;
case 505:
result = BASE_HTTP + "#sec10.5.6";
break;
case 507:
result = BASE_WEBDAV + "#STATUS_507";
break;
case 1000:
result = BASE_RESTLET
+ "org/restlet/data/Statuses.html#CONNECTOR_ERROR_CONNECTION";
break;
case 1001:
result = BASE_RESTLET
+ "org/restlet/data/Statuses.html#CONNECTOR_ERROR_COMMUNICATION";
break;
case 1002:
result = BASE_RESTLET
+ "org/restlet/data/Statuses.html#CONNECTOR_ERROR_INTERNAL";
break;
}
}
return result;
}
| public String getUri() {
String result = this.uri;
if (result == null) {
switch (this.code) {
case 100:
result = BASE_HTTP + "#sec10.1.1";
break;
case 101:
result = BASE_HTTP + "#sec10.1.2";
break;
case 102:
result = BASE_WEBDAV + "#STATUS_102";
break;
case 200:
result = BASE_HTTP + "#sec10.2.1";
break;
case 201:
result = BASE_HTTP + "#sec10.2.2";
break;
case 202:
result = BASE_HTTP + "#sec10.2.3";
break;
case 203:
result = BASE_HTTP + "#sec10.2.4";
break;
case 204:
result = BASE_HTTP + "#sec10.2.5";
break;
case 205:
result = BASE_HTTP + "#sec10.2.6";
break;
case 206:
result = BASE_HTTP + "#sec10.2.7";
break;
case 207:
result = BASE_WEBDAV + "#STATUS_207";
break;
case 300:
result = BASE_HTTP + "#sec10.3.1";
break;
case 301:
result = BASE_HTTP + "#sec10.3.2";
break;
case 302:
result = BASE_HTTP + "#sec10.3.3";
break;
case 303:
result = BASE_HTTP + "#sec10.3.4";
break;
case 304:
result = BASE_HTTP + "#sec10.3.5";
break;
case 305:
result = BASE_HTTP + "#sec10.3.6";
break;
case 307:
result = BASE_HTTP + "#sec10.3.8";
break;
case 400:
result = BASE_HTTP + "#sec10.4.1";
break;
case 401:
result = BASE_HTTP + "#sec10.4.2";
break;
case 402:
result = BASE_HTTP + "#sec10.4.3";
break;
case 403:
result = BASE_HTTP + "#sec10.4.4";
break;
case 404:
result = BASE_HTTP + "#sec10.4.5";
break;
case 405:
result = BASE_HTTP + "#sec10.4.6";
break;
case 406:
result = BASE_HTTP + "#sec10.4.7";
break;
case 407:
result = BASE_HTTP + "#sec10.4.8";
break;
case 408:
result = BASE_HTTP + "#sec10.4.9";
break;
case 409:
result = BASE_HTTP + "#sec10.4.10";
break;
case 410:
result = BASE_HTTP + "#sec10.4.11";
break;
case 411:
result = BASE_HTTP + "#sec10.4.12";
break;
case 412:
result = BASE_HTTP + "#sec10.4.13";
break;
case 413:
result = BASE_HTTP + "#sec10.4.14";
break;
case 414:
result = BASE_HTTP + "#sec10.4.15";
break;
case 415:
result = BASE_HTTP + "#sec10.4.16";
break;
case 416:
result = BASE_HTTP + "#sec10.4.17";
break;
case 417:
result = BASE_HTTP + "#sec10.4.18";
break;
case 422:
result = BASE_WEBDAV + "#STATUS_422";
break;
case 423:
result = BASE_WEBDAV + "#STATUS_423";
break;
case 424:
result = BASE_WEBDAV + "#STATUS_424";
break;
case 500:
result = BASE_HTTP + "#sec10.5.1";
break;
case 501:
result = BASE_HTTP + "#sec10.5.2";
break;
case 502:
result = BASE_HTTP + "#sec10.5.3";
break;
case 503:
result = BASE_HTTP + "#sec10.5.4";
break;
case 504:
result = BASE_HTTP + "#sec10.5.5";
break;
case 505:
result = BASE_HTTP + "#sec10.5.6";
break;
case 507:
result = BASE_WEBDAV + "#STATUS_507";
break;
case 1000:
result = BASE_RESTLET
+ "org/restlet/data/Status.html#CONNECTOR_ERROR_CONNECTION";
break;
case 1001:
result = BASE_RESTLET
+ "org/restlet/data/Status.html#CONNECTOR_ERROR_COMMUNICATION";
break;
case 1002:
result = BASE_RESTLET
+ "org/restlet/data/Status.html#CONNECTOR_ERROR_INTERNAL";
break;
}
}
return result;
}
|
diff --git a/src/main/java/hudson/plugins/mavendeploymentlinker/MavenDeploymentProjectLinkerAction.java b/src/main/java/hudson/plugins/mavendeploymentlinker/MavenDeploymentProjectLinkerAction.java
index 78dfc4e..d85fd3f 100644
--- a/src/main/java/hudson/plugins/mavendeploymentlinker/MavenDeploymentProjectLinkerAction.java
+++ b/src/main/java/hudson/plugins/mavendeploymentlinker/MavenDeploymentProjectLinkerAction.java
@@ -1,67 +1,67 @@
package hudson.plugins.mavendeploymentlinker;
import hudson.model.Action;
import hudson.model.AbstractProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.util.RunList;
import org.kohsuke.stapler.export.Exported;
public class MavenDeploymentProjectLinkerAction implements Action {
private final AbstractProject<?, ?> project;
public MavenDeploymentProjectLinkerAction(AbstractProject<?, ?> project) {
this.project = project;
}
public String getIconFileName() {
return null;
}
public String getDisplayName() {
return null;
}
public String getUrlName() {
return "";
}
@Exported
public boolean hasLatestDeployments() {
return getLatestDeployments() != null;
}
@Exported
public Action getLatestDeployments() {
Run lastSuccessfulBuild = project.getLastSuccessfulBuild();
if (lastSuccessfulBuild == null) {
return null;
}
return lastSuccessfulBuild.getAction(MavenDeploymentLinkerAction.class);
}
@Exported
public boolean hasLatestReleaseDeployments() {
return getLatestReleaseDeployments() != null;
}
@Exported
public Action getLatestReleaseDeployments() {
RunList<?> builds = project.getBuilds();
for (Run run : builds) {
if (isSuccessful(run)) {
MavenDeploymentLinkerAction linkerAction = run.getAction(MavenDeploymentLinkerAction.class);
- if (!linkerAction.isSnapshot()) {
+ if (linkerAction != null && !linkerAction.isSnapshot()) {
return linkerAction;
}
}
}
return null;
}
private boolean isSuccessful(Run run) {
return !(run.isBuilding() || run.getResult() == null || run.getResult().isWorseThan(Result.UNSTABLE));
}
}
| true | true | public Action getLatestReleaseDeployments() {
RunList<?> builds = project.getBuilds();
for (Run run : builds) {
if (isSuccessful(run)) {
MavenDeploymentLinkerAction linkerAction = run.getAction(MavenDeploymentLinkerAction.class);
if (!linkerAction.isSnapshot()) {
return linkerAction;
}
}
}
return null;
}
| public Action getLatestReleaseDeployments() {
RunList<?> builds = project.getBuilds();
for (Run run : builds) {
if (isSuccessful(run)) {
MavenDeploymentLinkerAction linkerAction = run.getAction(MavenDeploymentLinkerAction.class);
if (linkerAction != null && !linkerAction.isSnapshot()) {
return linkerAction;
}
}
}
return null;
}
|
diff --git a/webui/portal/src/main/java/org/exoplatform/portal/webui/login/UILoginForm.java b/webui/portal/src/main/java/org/exoplatform/portal/webui/login/UILoginForm.java
index 6c8b605e5..6eeaded2f 100644
--- a/webui/portal/src/main/java/org/exoplatform/portal/webui/login/UILoginForm.java
+++ b/webui/portal/src/main/java/org/exoplatform/portal/webui/login/UILoginForm.java
@@ -1,107 +1,107 @@
/*
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
*/
package org.exoplatform.portal.webui.login;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.webui.portal.UIPortal;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.portal.webui.workspace.UIMaskWorkspace;
import org.exoplatform.services.jcr.ext.organization.OrganizationServiceException;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.web.application.ApplicationMessage;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.exception.MessageException;
import org.exoplatform.webui.form.UIForm;
import org.exoplatform.webui.form.UIFormStringInput;
/**
* Created by The eXo Platform SARL
* Author : Nhu Dinh Thuan
* [email protected]
* Jul 11, 2006
*/
@ComponentConfig(
lifecycle = UIFormLifecycle.class,
template = "system:/groovy/portal/webui/UILoginForm.gtmpl" ,
events = {
@EventConfig(listeners = UILoginForm.SigninActionListener.class),
@EventConfig(phase = Phase.DECODE, listeners = UIMaskWorkspace.CloseActionListener.class),
@EventConfig(phase = Phase.DECODE, listeners = UILoginForm.ForgetPasswordActionListener.class)
}
)
public class UILoginForm extends UIForm {
final static String USER_NAME = "username";
final static String PASSWORD = "password";
public UILoginForm() throws Exception{
addUIFormInput(new UIFormStringInput(USER_NAME, USER_NAME, null)).
addUIFormInput(new UIFormStringInput(PASSWORD, PASSWORD, null).
setType(UIFormStringInput.PASSWORD_TYPE)) ;
}
static public class SigninActionListener extends EventListener<UILoginForm> {
public void execute(Event<UILoginForm> event) throws Exception {
UILoginForm uiForm = event.getSource();
String username = uiForm.getUIStringInput(USER_NAME).getValue();
String password = uiForm.getUIStringInput(PASSWORD).getValue();
OrganizationService orgService = uiForm.getApplicationComponent(OrganizationService.class);
// TODO:
try{
- //boolean authentication = orgService.getUserHandler().authenticate(username, password);
+ boolean authentication = orgService.getUserHandler().authenticate(username, password);
} catch (Exception e) {
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}
/*if(!authentication){
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}*/
PortalRequestContext prContext = Util.getPortalRequestContext();
HttpServletRequest request = prContext.getRequest();
HttpSession session = request.getSession();
session.setAttribute("authentication.username", username);
session.setAttribute("authentication.password", password);
UIPortal uiPortal = Util.getUIPortal();
prContext.setResponseComplete(true);
String portalName = uiPortal.getName() ;
portalName = URLEncoder.encode(portalName, "UTF-8") ;
String redirect = request.getContextPath() + "/private/" + portalName + "/";
prContext.getResponse().sendRedirect(redirect);
}
}
//TODO: dang.tung - forget password
static public class ForgetPasswordActionListener extends EventListener<UILoginForm> {
public void execute(Event<UILoginForm> event) throws Exception {
UILogin uiLogin = event.getSource().getParent();
uiLogin.getChild(UILoginForm.class).setRendered(false);
uiLogin.getChild(UIForgetPasswordWizard.class).setRendered(true);
event.getRequestContext().addUIComponentToUpdateByAjax(uiLogin);
}
}
}
| true | true | public void execute(Event<UILoginForm> event) throws Exception {
UILoginForm uiForm = event.getSource();
String username = uiForm.getUIStringInput(USER_NAME).getValue();
String password = uiForm.getUIStringInput(PASSWORD).getValue();
OrganizationService orgService = uiForm.getApplicationComponent(OrganizationService.class);
// TODO:
try{
//boolean authentication = orgService.getUserHandler().authenticate(username, password);
} catch (Exception e) {
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}
/*if(!authentication){
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}*/
| public void execute(Event<UILoginForm> event) throws Exception {
UILoginForm uiForm = event.getSource();
String username = uiForm.getUIStringInput(USER_NAME).getValue();
String password = uiForm.getUIStringInput(PASSWORD).getValue();
OrganizationService orgService = uiForm.getApplicationComponent(OrganizationService.class);
// TODO:
try{
boolean authentication = orgService.getUserHandler().authenticate(username, password);
} catch (Exception e) {
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}
/*if(!authentication){
throw new MessageException(new ApplicationMessage("UILoginForm.msg.Invalid-account", null));
}*/
|
diff --git a/ace/component/src/org/icefaces/ace/component/menu/BaseMenuRenderer.java b/ace/component/src/org/icefaces/ace/component/menu/BaseMenuRenderer.java
index aba66372d..cd6020951 100644
--- a/ace/component/src/org/icefaces/ace/component/menu/BaseMenuRenderer.java
+++ b/ace/component/src/org/icefaces/ace/component/menu/BaseMenuRenderer.java
@@ -1,173 +1,173 @@
/*
* Original Code developed and contributed by Prime Technology.
* Subsequent Code Modifications Copyright 2011 ICEsoft Technologies Canada Corp. (c)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* NOTE THIS CODE HAS BEEN MODIFIED FROM ORIGINAL FORM
*
* Subsequent Code Modifications have been made and contributed by ICEsoft Technologies Canada Corp. (c).
*
* Code Modification 1: Integrated with ICEfaces Advanced Component Environment.
* Contributors: ICEsoft Technologies Canada Corp. (c)
*
* Code Modification 2: [ADD BRIEF DESCRIPTION HERE]
* Contributors: ______________________
* Contributors: ______________________
*/
package org.icefaces.ace.component.menu;
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.icefaces.ace.component.menuitem.MenuItem;
import org.icefaces.ace.renderkit.CoreRenderer;
import org.icefaces.ace.util.ComponentUtils;
import org.icefaces.ace.util.Utils;
import org.icefaces.impl.event.AjaxDisabledList;
import javax.faces.component.behavior.ClientBehavior;
import javax.faces.component.behavior.ClientBehaviorContext;
import javax.faces.component.behavior.ClientBehaviorHolder;
import java.util.*;
import org.icefaces.ace.component.ajax.AjaxBehavior;
public abstract class BaseMenuRenderer extends CoreRenderer {
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
AbstractMenu menu = (AbstractMenu) component;
if(menu.shouldBuildFromModel()) {
menu.buildMenuFromModel();
}
encodeMarkup(context, menu);
encodeScript(context, menu);
}
protected abstract void encodeMarkup(FacesContext context, AbstractMenu abstractMenu) throws IOException;
protected abstract void encodeScript(FacesContext context, AbstractMenu abstractMenu) throws IOException;
protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException {
String clientId = menuItem.getClientId(context);
ResponseWriter writer = context.getResponseWriter();
String icon = menuItem.getIcon();
if(menuItem.shouldRenderChildren()) {
renderChildren(context, menuItem);
}
else {
writer.startElement("a", null);
if(menuItem.getUrl() != null) {
writer.writeAttribute("href", getResourceURL(context, menuItem.getUrl()), null);
if(menuItem.getOnclick() != null) writer.writeAttribute("onclick", menuItem.getOnclick(), null);
if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null);
} else {
writer.writeAttribute("href", "#", null);
UIComponent form = ComponentUtils.findParentForm(context, menuItem);
if(form == null) {
throw new FacesException("Menubar must be inside a form element");
}
String formClientId = form.getClientId(context);
String command;
boolean hasAjaxBehavior = false;
StringBuilder behaviors = new StringBuilder();
behaviors.append("var self = this; setTimeout(function() { var f = function(){"); // dynamically set the id to the node so that it can be handled by the submit functions
// ClientBehaviors
Map<String,List<ClientBehavior>> behaviorEvents = menuItem.getClientBehaviors();
if(!behaviorEvents.isEmpty()) {
List<ClientBehaviorContext.Parameter> params = Collections.emptyList();
for(Iterator<ClientBehavior> behaviorIter = behaviorEvents.get("activate").iterator(); behaviorIter.hasNext();) {
ClientBehavior behavior = behaviorIter.next();
if (behavior instanceof AjaxBehavior)
hasAjaxBehavior = true;
ClientBehaviorContext cbc = ClientBehaviorContext.createClientBehaviorContext(context, menuItem, "activate", clientId, params);
String script = behavior.getScript(cbc); //could be null if disabled
if(script != null) {
behaviors.append(script);
behaviors.append(";");
}
}
}
- behaviors.append("}; f({'ice.customUpdate':'" + clientId +"'}, null, null, self); }, 10);");
+ behaviors.append("}; f(null, null, null, self); }, 10);");
command = behaviors.toString();
if (!hasAjaxBehavior && (menuItem.getActionExpression() != null || menuItem.getActionListeners().length > 0)) {
command += "ice.s(event, this";
StringBuilder parameters = new StringBuilder();
parameters.append(",function(p){");
for(UIComponent child : menuItem.getChildren()) {
if(child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
parameters.append("p('");
parameters.append(param.getName());
parameters.append("','");
parameters.append(String.valueOf(param.getValue()));
parameters.append("');");
}
}
parameters.append("});");
command += parameters.toString();
}
command = menuItem.getOnclick() == null ? command : menuItem.getOnclick() + ";" + command;
writer.writeAttribute("onclick", command, null);
}
if(icon != null) {
writer.startElement("span", null);
writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null);
writer.endElement("span");
}
if(menuItem.getValue() != null) {
writer.startElement("span", null);
String style = menuItem.getStyle();
if (style != null && style.trim().length() > 0) {
writer.writeAttribute("style", style, "style");
}
Utils.writeConcatenatedStyleClasses(writer, "wijmo-wijmenu-text", menuItem.getStyleClass());
writer.write((String) menuItem.getValue());
writer.endElement("span");
}
writer.endElement("a");
}
}
@Override
public void encodeChildren(FacesContext facesContext, UIComponent component) throws IOException {
//Do nothing
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| true | true | protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException {
String clientId = menuItem.getClientId(context);
ResponseWriter writer = context.getResponseWriter();
String icon = menuItem.getIcon();
if(menuItem.shouldRenderChildren()) {
renderChildren(context, menuItem);
}
else {
writer.startElement("a", null);
if(menuItem.getUrl() != null) {
writer.writeAttribute("href", getResourceURL(context, menuItem.getUrl()), null);
if(menuItem.getOnclick() != null) writer.writeAttribute("onclick", menuItem.getOnclick(), null);
if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null);
} else {
writer.writeAttribute("href", "#", null);
UIComponent form = ComponentUtils.findParentForm(context, menuItem);
if(form == null) {
throw new FacesException("Menubar must be inside a form element");
}
String formClientId = form.getClientId(context);
String command;
boolean hasAjaxBehavior = false;
StringBuilder behaviors = new StringBuilder();
behaviors.append("var self = this; setTimeout(function() { var f = function(){"); // dynamically set the id to the node so that it can be handled by the submit functions
// ClientBehaviors
Map<String,List<ClientBehavior>> behaviorEvents = menuItem.getClientBehaviors();
if(!behaviorEvents.isEmpty()) {
List<ClientBehaviorContext.Parameter> params = Collections.emptyList();
for(Iterator<ClientBehavior> behaviorIter = behaviorEvents.get("activate").iterator(); behaviorIter.hasNext();) {
ClientBehavior behavior = behaviorIter.next();
if (behavior instanceof AjaxBehavior)
hasAjaxBehavior = true;
ClientBehaviorContext cbc = ClientBehaviorContext.createClientBehaviorContext(context, menuItem, "activate", clientId, params);
String script = behavior.getScript(cbc); //could be null if disabled
if(script != null) {
behaviors.append(script);
behaviors.append(";");
}
}
}
behaviors.append("}; f({'ice.customUpdate':'" + clientId +"'}, null, null, self); }, 10);");
command = behaviors.toString();
if (!hasAjaxBehavior && (menuItem.getActionExpression() != null || menuItem.getActionListeners().length > 0)) {
command += "ice.s(event, this";
StringBuilder parameters = new StringBuilder();
parameters.append(",function(p){");
for(UIComponent child : menuItem.getChildren()) {
if(child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
parameters.append("p('");
parameters.append(param.getName());
parameters.append("','");
parameters.append(String.valueOf(param.getValue()));
parameters.append("');");
}
}
parameters.append("});");
command += parameters.toString();
}
command = menuItem.getOnclick() == null ? command : menuItem.getOnclick() + ";" + command;
writer.writeAttribute("onclick", command, null);
}
if(icon != null) {
writer.startElement("span", null);
writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null);
writer.endElement("span");
}
if(menuItem.getValue() != null) {
writer.startElement("span", null);
String style = menuItem.getStyle();
if (style != null && style.trim().length() > 0) {
writer.writeAttribute("style", style, "style");
}
Utils.writeConcatenatedStyleClasses(writer, "wijmo-wijmenu-text", menuItem.getStyleClass());
writer.write((String) menuItem.getValue());
writer.endElement("span");
}
writer.endElement("a");
}
}
| protected void encodeMenuItem(FacesContext context, MenuItem menuItem) throws IOException {
String clientId = menuItem.getClientId(context);
ResponseWriter writer = context.getResponseWriter();
String icon = menuItem.getIcon();
if(menuItem.shouldRenderChildren()) {
renderChildren(context, menuItem);
}
else {
writer.startElement("a", null);
if(menuItem.getUrl() != null) {
writer.writeAttribute("href", getResourceURL(context, menuItem.getUrl()), null);
if(menuItem.getOnclick() != null) writer.writeAttribute("onclick", menuItem.getOnclick(), null);
if(menuItem.getTarget() != null) writer.writeAttribute("target", menuItem.getTarget(), null);
} else {
writer.writeAttribute("href", "#", null);
UIComponent form = ComponentUtils.findParentForm(context, menuItem);
if(form == null) {
throw new FacesException("Menubar must be inside a form element");
}
String formClientId = form.getClientId(context);
String command;
boolean hasAjaxBehavior = false;
StringBuilder behaviors = new StringBuilder();
behaviors.append("var self = this; setTimeout(function() { var f = function(){"); // dynamically set the id to the node so that it can be handled by the submit functions
// ClientBehaviors
Map<String,List<ClientBehavior>> behaviorEvents = menuItem.getClientBehaviors();
if(!behaviorEvents.isEmpty()) {
List<ClientBehaviorContext.Parameter> params = Collections.emptyList();
for(Iterator<ClientBehavior> behaviorIter = behaviorEvents.get("activate").iterator(); behaviorIter.hasNext();) {
ClientBehavior behavior = behaviorIter.next();
if (behavior instanceof AjaxBehavior)
hasAjaxBehavior = true;
ClientBehaviorContext cbc = ClientBehaviorContext.createClientBehaviorContext(context, menuItem, "activate", clientId, params);
String script = behavior.getScript(cbc); //could be null if disabled
if(script != null) {
behaviors.append(script);
behaviors.append(";");
}
}
}
behaviors.append("}; f(null, null, null, self); }, 10);");
command = behaviors.toString();
if (!hasAjaxBehavior && (menuItem.getActionExpression() != null || menuItem.getActionListeners().length > 0)) {
command += "ice.s(event, this";
StringBuilder parameters = new StringBuilder();
parameters.append(",function(p){");
for(UIComponent child : menuItem.getChildren()) {
if(child instanceof UIParameter) {
UIParameter param = (UIParameter) child;
parameters.append("p('");
parameters.append(param.getName());
parameters.append("','");
parameters.append(String.valueOf(param.getValue()));
parameters.append("');");
}
}
parameters.append("});");
command += parameters.toString();
}
command = menuItem.getOnclick() == null ? command : menuItem.getOnclick() + ";" + command;
writer.writeAttribute("onclick", command, null);
}
if(icon != null) {
writer.startElement("span", null);
writer.writeAttribute("class", icon + " wijmo-wijmenu-icon-left", null);
writer.endElement("span");
}
if(menuItem.getValue() != null) {
writer.startElement("span", null);
String style = menuItem.getStyle();
if (style != null && style.trim().length() > 0) {
writer.writeAttribute("style", style, "style");
}
Utils.writeConcatenatedStyleClasses(writer, "wijmo-wijmenu-text", menuItem.getStyleClass());
writer.write((String) menuItem.getValue());
writer.endElement("span");
}
writer.endElement("a");
}
}
|
diff --git a/src/com/motorola/android/fmradio/FMRadioService.java b/src/com/motorola/android/fmradio/FMRadioService.java
index 78763bc..da5cf79 100644
--- a/src/com/motorola/android/fmradio/FMRadioService.java
+++ b/src/com/motorola/android/fmradio/FMRadioService.java
@@ -1,782 +1,782 @@
package com.motorola.android.fmradio;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.SystemService;
import android.util.Log;
import com.motorola.android.fmradio.FMRadioPlayer.OnCommandCompleteListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class FMRadioService extends Service implements IFMCommand {
private static final String TAG = "FMRadioService";
private static final boolean LOGV = true;
/* service name of fmradioserver */
private static final String SERVICE_FMRADIO = "fmradio";
private boolean mBeginInvokeCB = false;
private List<CBEntity> mCBList = new ArrayList<CBEntity>();
final RemoteCallbackList<IFMRadioServiceCallback> mCallbacks =
new RemoteCallbackList<IFMRadioServiceCallback>();
private boolean mIgnoreCallBack = false;
private int mBand = IFMRadioConstant.FMRADIO_BAND0;
private int mCurrentFreq;
private int mEdgeSeekCount = 0;
private List<Integer> mFMCmdList = new ArrayList<Integer>();
private FMRadioPlayer mFMRadioJNI;
private boolean mScanning = false;
private boolean mStopScan = true;
private boolean mIsEnable = false;
private boolean mRdsEnabled = false;
private boolean mScanBegin = false;
private boolean mSeekWrap = false;
private boolean mPowerOffComplete = false;
private int mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
private int mRdsMode = -1;
private int mRdsPI;
private String mRdsPS;
private int mRdsPTY;
private String mRdsRT;
private String mRdsRTPlus;
private static class CBEntity {
int cmd;
int status;
Object value;
CBEntity(int cmd, int status, Object value) {
this.cmd = cmd;
this.status = status;
this.value = value;
}
};
private final OnCommandCompleteListener mCommandComplListener = new OnCommandCompleteListener() {
private boolean enableCompleted(List<CBEntity> list) {
boolean rst = false;
int enableCount = 0;
int tuneCount = 0;
int setBandCount = 0;
int setRSSICount = 0;
if (list == null || list.isEmpty()) {
return false;
}
for (int i = 0; i < list.size(); i++) {
int cmd = list.get(i).cmd;
if (cmd == IFMCommand.FM_CMD_ENABLE_COMPLETE) {
enableCount++;
} else if (cmd == IFMCommand.FM_CMD_TUNE_COMPLETE) {
tuneCount++;
} else if (cmd == IFMCommand.FM_CMD_SET_BAND_DONE) {
setBandCount++;
} else if (cmd == IFMCommand.FM_CMD_SET_RSSI_DONE) {
setRSSICount++;
}
}
if (enableCount >= 1 && tuneCount >= 2 && setBandCount >= 1 && setRSSICount >= 1) {
return true;
}
return false;
}
public void onCommandComplete(int cmd, int status, Object value) {
if (LOGV) Log.v(TAG, "onCommandComplete, cmd = " + cmd + " status = " + status + " value = " + value);
FMRadioUtil.checkCmdInList(cmd, mFMCmdList);
switch (cmd) {
case IFMCommand.FM_CMD_TUNE_COMPLETE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
resetRdsData();
if (mIsEnable) {
mIsEnable = false;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
int bandForHAL = FMRadioUtil.getBandForStack(mBand);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.setBand(bandForHAL)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mScanning && mScanBegin) {
mIgnoreCallBack = true;
mScanBegin = false;
cmd = IFMCommand.FM_CMD_NONE;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else if (mSeeking != IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE) {
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
mIgnoreCallBack = true;
mSeekWrap = true;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(mSeeking)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
break;
case IFMCommand.FM_CMD_SEEK_COMPLETE:
resetRdsData();
if (!mScanning && FMRadioUtil.checkInt(value)) {
mCurrentFreq = (Integer) value;
if (status == IFMRadioConstant.FMRADIO_STATUS_FAIL) {
if (mSeekWrap) {
mSeekWrap = false;
mIgnoreCallBack = false;
} else {
mIgnoreCallBack = true;
}
if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMinFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_DOWN;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMaxFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else {
mEdgeSeekCount = 0;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
if (mScanning) {
if (FMRadioUtil.checkStatusAndInt(status, value)) {
int soughtFreq = (Integer) value;
- if (mCurrentFreq > soughtFreq) {
+ if (mCurrentFreq < soughtFreq) {
mCurrentFreq = soughtFreq;
cmd = IFMCommand.FM_CMD_SCANNING;
if (mStopScan) {
mScanning = false;
cmd = IFMCommand.FM_CMD_ABORT_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
} else if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_SCAN_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
} else /* checkstatus */ {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
}
break;
case IFMCommand.FM_CMD_ABORT_COMPLETE:
case IFMCommand.FM_CMD_GET_FREQ_DONE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsPS = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_RT_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRT = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_PI_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPI = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PTY_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPTY = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_RTPLUS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRTPlus = (String) value;
}
break;
case IFMCommand.FM_CMD_ENABLE_COMPLETE:
mIsEnable = true;
break;
case IFMCommand.FM_CMD_DISABLE_COMPLETE:
mPowerOffComplete = true;
break;
case IFMCommand.FM_CMD_ENABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = true;
}
break;
case IFMCommand.FM_CMD_DISABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = false;
}
break;
}
if (mBeginInvokeCB) {
if (!mIgnoreCallBack) {
invokeCallback(cmd, status, value);
} else {
mIgnoreCallBack = false;
}
} else {
if (cmd == IFMCommand.FM_CMD_TUNE_COMPLETE || cmd == IFMCommand.FM_CMD_ENABLE_COMPLETE
|| cmd == IFMCommand.FM_CMD_SET_BAND_DONE || cmd == IFMCommand.FM_CMD_SET_RSSI_DONE) {
CBEntity cb = new CBEntity(cmd, status, value);
mCBList.add(cb);
}
if (enableCompleted(mCBList)) {
mBeginInvokeCB = true;
CBEntity cbEnable = getCBForEnable(mCBList);
if (cbEnable != null) {
invokeCallback(cbEnable.cmd, cbEnable.status, cbEnable.value);
}
CBEntity cbTune = getCBForTune(mCBList);
if (cbTune != null) {
invokeCallback(cbTune.cmd, cbTune.status, cbTune.value);
}
mCBList.clear();
}
}
}
};
private final IFMRadioService.Stub mBinder = new IFMRadioService.Stub() {
@Override
public boolean getAudioMode() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_AUDIOMODE_DONE, mFMCmdList);
result = mFMRadioJNI.getAudioMode();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_AUDIOMODE_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean getAudioType() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_AUDIOTYPE_DONE, mFMCmdList);
result = mFMRadioJNI.getAudioType();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_AUDIOTYPE_DONE, mFMCmdList);
}
}
return result;
}
@Override
public int getBand() throws RemoteException {
return mBand;
}
@Override
public boolean getCurrentFreq() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_FREQ_DONE, mFMCmdList);
result = mFMRadioJNI.currentFreq();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_FREQ_DONE, mFMCmdList);
}
}
return result;
}
@Override
public int getMaxFrequence() throws RemoteException {
return getMaxFreq();
}
@Override
public int getMinFrequence() throws RemoteException {
return getMinFreq();
}
@Override
public String getRDSStationName() {
if (mRdsMode == IFMRadioConstant.FMRADIO_RDS_MODE_RDS && !mRdsPS.equals("")) {
return mRdsPS;
} else if (mRdsMode == IFMRadioConstant.FMRADIO_RDS_MODE_RBDS && mRdsPI != -1) {
char[] piArray = FMRadioUtil.decodePI(mRdsPI);
if (piArray != null) {
return new String(piArray);
}
}
return "";
}
@Override
public boolean getRSSI() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_RSSI_DONE, mFMCmdList);
result = mFMRadioJNI.getRSSI();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_RSSI_DONE, mFMCmdList);
}
}
return result;
}
@Override
public int getRdsPI() {
return mRdsPI;
}
@Override
public String getRdsPS() throws RemoteException {
return mRdsPS;
}
@Override
public int getRdsPTY() throws RemoteException {
return mRdsPTY;
}
@Override
public String getRdsRT() throws RemoteException {
return mRdsRT;
}
@Override
public String getRdsRTPLUS() throws RemoteException {
return mRdsRTPlus;
}
@Override
public int getStepUnit() throws RemoteException {
return getUnit();
}
@Override
public boolean getVolume() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_VOLUME_DONE, mFMCmdList);
result = mFMRadioJNI.getVolume();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_VOLUME_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean isMute() throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_GET_MUTE_DONE, mFMCmdList);
result = mFMRadioJNI.isMute();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_GET_MUTE_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean isRdsEnable() throws RemoteException {
return mRdsEnabled;
}
@Override
public void registerCallback(IFMRadioServiceCallback cb) throws RemoteException {
if (cb != null) {
mCallbacks.register(cb);
}
}
@Override
public void unregisterCallback(IFMRadioServiceCallback cb) throws RemoteException {
if (cb != null) {
mCallbacks.unregister(cb);
}
}
@Override
public boolean scan() throws RemoteException {
boolean result = false;
mScanning = true;
mScanBegin = true;
mStopScan = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
result = mFMRadioJNI.tune(getMinFreq());
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
}
return result;
}
@Override
public boolean seek(int direction) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
result = mFMRadioJNI.seek(direction);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
return result;
}
@Override
public boolean setAudioMode(int mode) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_AUDIOMODE_DONE, mFMCmdList);
result = mFMRadioJNI.setAudioMode(mode);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_AUDIOMODE_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean setBand(int band) throws RemoteException {
boolean result = false;
int bandForHAL = FMRadioUtil.getBandForStack(band);
mBand = band;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
result = mFMRadioJNI.setBand(bandForHAL);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
}
return result;
}
@Override
public boolean setMute(int mode) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_AUDIOMUTE_DONE, mFMCmdList);
result = mFMRadioJNI.setMute(mode);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_AUDIOMUTE_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean setRSSI(int rssi) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_RSSI_DONE, mFMCmdList);
result = mFMRadioJNI.setRSSI(rssi);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_RSSI_DONE, mFMCmdList);
}
}
return result;
}
@Override
public boolean setRdsEnable(boolean flag, int mode) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
if (flag) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_ENABLE_RDS_DONE, mFMCmdList);
result = mFMRadioJNI.enableRDS(mode);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_ENABLE_RDS_DONE, mFMCmdList);
} else {
mRdsMode = mode;
}
} else {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_DISABLE_RDS_DONE, mFMCmdList);
result = mFMRadioJNI.disableRDS();
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_DISABLE_RDS_DONE, mFMCmdList);
} else {
mRdsMode = -1;
}
}
}
return result;
}
@Override
public boolean setVolume(int volume) throws RemoteException {
return mFMRadioJNI.setVolume(volume);
}
@Override
public boolean stopScan() throws RemoteException {
mStopScan = true;
return true;
}
@Override
public boolean stopSeek() throws RemoteException {
if (mFMRadioJNI.stopSeek()) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
return true;
}
return false;
}
@Override
public boolean tune(int freq) throws RemoteException {
boolean result = false;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
result = mFMRadioJNI.tune(freq);
if (!result) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
}
return result;
}
};
public FMRadioService() {
super();
resetRdsData();
}
@Override
public IBinder onBind(Intent intent) {
if (LOGV) Log.v(TAG, "onBind()");
SystemService.start(SERVICE_FMRADIO);
mFMRadioJNI = new FMRadioPlayer();
mFMRadioJNI.setOnCommandCompleteListener(mCommandComplListener);
mFMCmdList.clear();
mCBList.clear();
mBeginInvokeCB = false;
mIgnoreCallBack = false;
mSeekWrap = false;
mFMRadioJNI.powerOnDevice(0);
mBand = FMRadioUtil.getBandByLocale(getResources().getConfiguration().locale);
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
if (LOGV) Log.v(TAG, "onCreate()");
mBeginInvokeCB = false;
}
@Override
public void onRebind(Intent intent) {
if (LOGV) Log.v(TAG, "onRebind()");
SystemService.start(SERVICE_FMRADIO);
mFMRadioJNI = new FMRadioPlayer();
mFMRadioJNI.setOnCommandCompleteListener(mCommandComplListener);
mFMCmdList.clear();
mCBList.clear();
mBeginInvokeCB = false;
mIgnoreCallBack = false;
mSeekWrap = false;
mFMRadioJNI.powerOnDevice(0);
}
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
if (LOGV) Log.v(TAG, "onUnbind()");
mFMCmdList.clear();
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_DISABLE_COMPLETE, mFMCmdList);
mFMRadioJNI.powerOffDevice();
FMRadioUtil.sleep(FMRadioUtil.FM_POWEROFF_TIME);
mFMCmdList.clear();
mCallbacks.kill();
mFMRadioJNI.setOnCommandCompleteListener(null);
SystemService.stop(SERVICE_FMRADIO);
return true;
}
private int getMinFreq() {
switch (mBand) {
case IFMRadioConstant.FMRADIO_BAND0:
return IFMRadioConstant.FMRADIO_BAND0_MIN_FREQ;
case IFMRadioConstant.FMRADIO_BAND1:
return IFMRadioConstant.FMRADIO_BAND1_MIN_FREQ;
case IFMRadioConstant.FMRADIO_BAND2:
return IFMRadioConstant.FMRADIO_BAND2_MIN_FREQ;
case IFMRadioConstant.FMRADIO_BAND3:
return IFMRadioConstant.FMRADIO_BAND3_MIN_FREQ;
}
return IFMRadioConstant.FMRADIO_BAND0_MIN_FREQ;
}
private int getMaxFreq() {
switch (mBand) {
case IFMRadioConstant.FMRADIO_BAND0:
return IFMRadioConstant.FMRADIO_BAND0_MAX_FREQ;
case IFMRadioConstant.FMRADIO_BAND1:
return IFMRadioConstant.FMRADIO_BAND1_MAX_FREQ;
case IFMRadioConstant.FMRADIO_BAND2:
return IFMRadioConstant.FMRADIO_BAND2_MAX_FREQ;
case IFMRadioConstant.FMRADIO_BAND3:
return IFMRadioConstant.FMRADIO_BAND3_MAX_FREQ;
}
return IFMRadioConstant.FMRADIO_BAND0_MAX_FREQ;
}
private int getUnit() {
switch (mBand) {
case IFMRadioConstant.FMRADIO_BAND0:
return IFMRadioConstant.FMRADIO_BAND0_STEP;
case IFMRadioConstant.FMRADIO_BAND1:
return IFMRadioConstant.FMRADIO_BAND1_STEP;
case IFMRadioConstant.FMRADIO_BAND2:
return IFMRadioConstant.FMRADIO_BAND2_STEP;
case IFMRadioConstant.FMRADIO_BAND3:
return IFMRadioConstant.FMRADIO_BAND3_STEP;
}
return IFMRadioConstant.FMRADIO_BAND0_STEP;
}
private void invokeCallback(int cmd, int status, Object value) {
if (mCallbacks == null) {
return;
}
int N = mCallbacks.beginBroadcast();
if (LOGV) {
Log.v(TAG, "N = " + N);
}
for (int i = 0; i < N; i++) {
if (value != null) {
try {
IFMRadioServiceCallback callback = mCallbacks.getBroadcastItem(i);
callback.onCommandComplete(cmd, status, value.toString());
} catch (RemoteException e) {
Log.d(TAG, "Could not invoke service callback", e);
}
}
}
mCallbacks.finishBroadcast();
}
private void resetRdsData() {
mRdsPI = -1;
mRdsPS = "";
mRdsPTY = -1;
mRdsRT = "";
mRdsRTPlus = "";
}
protected CBEntity getCBForEnable(List<CBEntity> cbList) {
CBEntity cb = null;
if (cbList == null) {
return null;
}
for (CBEntity item : cbList) {
if (item.cmd == IFMCommand.FM_CMD_ENABLE_COMPLETE) {
cb = item;
break;
}
}
return cb;
}
protected CBEntity getCBForTune(List<CBEntity> cbList) {
CBEntity cb = null;
if (cbList == null || cbList.isEmpty()) {
return null;
}
for (int i = cbList.size() - 1; i >= 0; i--) {
CBEntity item = cbList.get(i);
if (item.cmd == IFMCommand.FM_CMD_TUNE_COMPLETE) {
cb = item;
break;
}
}
return cb;
}
}
| true | true | public void onCommandComplete(int cmd, int status, Object value) {
if (LOGV) Log.v(TAG, "onCommandComplete, cmd = " + cmd + " status = " + status + " value = " + value);
FMRadioUtil.checkCmdInList(cmd, mFMCmdList);
switch (cmd) {
case IFMCommand.FM_CMD_TUNE_COMPLETE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
resetRdsData();
if (mIsEnable) {
mIsEnable = false;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
int bandForHAL = FMRadioUtil.getBandForStack(mBand);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.setBand(bandForHAL)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mScanning && mScanBegin) {
mIgnoreCallBack = true;
mScanBegin = false;
cmd = IFMCommand.FM_CMD_NONE;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else if (mSeeking != IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE) {
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
mIgnoreCallBack = true;
mSeekWrap = true;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(mSeeking)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
break;
case IFMCommand.FM_CMD_SEEK_COMPLETE:
resetRdsData();
if (!mScanning && FMRadioUtil.checkInt(value)) {
mCurrentFreq = (Integer) value;
if (status == IFMRadioConstant.FMRADIO_STATUS_FAIL) {
if (mSeekWrap) {
mSeekWrap = false;
mIgnoreCallBack = false;
} else {
mIgnoreCallBack = true;
}
if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMinFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_DOWN;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMaxFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else {
mEdgeSeekCount = 0;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
if (mScanning) {
if (FMRadioUtil.checkStatusAndInt(status, value)) {
int soughtFreq = (Integer) value;
if (mCurrentFreq > soughtFreq) {
mCurrentFreq = soughtFreq;
cmd = IFMCommand.FM_CMD_SCANNING;
if (mStopScan) {
mScanning = false;
cmd = IFMCommand.FM_CMD_ABORT_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
} else if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_SCAN_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
} else /* checkstatus */ {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
}
break;
case IFMCommand.FM_CMD_ABORT_COMPLETE:
case IFMCommand.FM_CMD_GET_FREQ_DONE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsPS = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_RT_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRT = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_PI_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPI = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PTY_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPTY = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_RTPLUS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRTPlus = (String) value;
}
break;
case IFMCommand.FM_CMD_ENABLE_COMPLETE:
mIsEnable = true;
break;
case IFMCommand.FM_CMD_DISABLE_COMPLETE:
mPowerOffComplete = true;
break;
case IFMCommand.FM_CMD_ENABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = true;
}
break;
case IFMCommand.FM_CMD_DISABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = false;
}
break;
}
if (mBeginInvokeCB) {
if (!mIgnoreCallBack) {
invokeCallback(cmd, status, value);
} else {
mIgnoreCallBack = false;
}
} else {
if (cmd == IFMCommand.FM_CMD_TUNE_COMPLETE || cmd == IFMCommand.FM_CMD_ENABLE_COMPLETE
|| cmd == IFMCommand.FM_CMD_SET_BAND_DONE || cmd == IFMCommand.FM_CMD_SET_RSSI_DONE) {
CBEntity cb = new CBEntity(cmd, status, value);
mCBList.add(cb);
}
if (enableCompleted(mCBList)) {
mBeginInvokeCB = true;
CBEntity cbEnable = getCBForEnable(mCBList);
if (cbEnable != null) {
invokeCallback(cbEnable.cmd, cbEnable.status, cbEnable.value);
}
CBEntity cbTune = getCBForTune(mCBList);
if (cbTune != null) {
invokeCallback(cbTune.cmd, cbTune.status, cbTune.value);
}
mCBList.clear();
}
}
}
| public void onCommandComplete(int cmd, int status, Object value) {
if (LOGV) Log.v(TAG, "onCommandComplete, cmd = " + cmd + " status = " + status + " value = " + value);
FMRadioUtil.checkCmdInList(cmd, mFMCmdList);
switch (cmd) {
case IFMCommand.FM_CMD_TUNE_COMPLETE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
resetRdsData();
if (mIsEnable) {
mIsEnable = false;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
int bandForHAL = FMRadioUtil.getBandForStack(mBand);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.setBand(bandForHAL)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SET_BAND_DONE, mFMCmdList);
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mScanning && mScanBegin) {
mIgnoreCallBack = true;
mScanBegin = false;
cmd = IFMCommand.FM_CMD_NONE;
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else if (mSeeking != IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE) {
if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
mIgnoreCallBack = true;
mSeekWrap = true;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(mSeeking)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
break;
case IFMCommand.FM_CMD_SEEK_COMPLETE:
resetRdsData();
if (!mScanning && FMRadioUtil.checkInt(value)) {
mCurrentFreq = (Integer) value;
if (status == IFMRadioConstant.FMRADIO_STATUS_FAIL) {
if (mSeekWrap) {
mSeekWrap = false;
mIgnoreCallBack = false;
} else {
mIgnoreCallBack = true;
}
if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMinFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else if (mCurrentFreq == getMaxFreq() && FMRadioUtil.checkCmdListComplete(mFMCmdList) && mEdgeSeekCount == 0) {
mEdgeSeekCount++;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_DOWN;
FMRadioUtil.sleep(FMRadioUtil.FM_CMD_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.tune(getMaxFreq())) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_TUNE_COMPLETE, mFMCmdList);
}
} else {
mEdgeSeekCount = 0;
mSeeking = IFMRadioConstant.FMRADIO_SEEK_DIRECTION_NONE;
}
}
}
if (mScanning) {
if (FMRadioUtil.checkStatusAndInt(status, value)) {
int soughtFreq = (Integer) value;
if (mCurrentFreq < soughtFreq) {
mCurrentFreq = soughtFreq;
cmd = IFMCommand.FM_CMD_SCANNING;
if (mStopScan) {
mScanning = false;
cmd = IFMCommand.FM_CMD_ABORT_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
} else if (FMRadioUtil.checkCmdListComplete(mFMCmdList)) {
FMRadioUtil.sleep(FMRadioUtil.FM_SCAN_INTERVAL);
FMRadioUtil.addCmdToList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
if (!mFMRadioJNI.seek(IFMRadioConstant.FMRADIO_SEEK_DIRECTION_UP)) {
FMRadioUtil.removeCmdFromList(IFMCommand.FM_CMD_SEEK_COMPLETE, mFMCmdList);
}
}
} else {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
} else /* checkstatus */ {
cmd = IFMCommand.FM_CMD_SCAN_COMPLETE;
status = IFMRadioConstant.FMRADIO_STATUS_OK;
mScanning = false;
value = Integer.valueOf(-1);
}
}
break;
case IFMCommand.FM_CMD_ABORT_COMPLETE:
case IFMCommand.FM_CMD_GET_FREQ_DONE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mCurrentFreq = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsPS = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_RT_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRT = (String) value;
}
break;
case IFMCommand.FM_CMD_RDS_PI_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPI = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_PTY_AVAILABLE:
if (FMRadioUtil.checkStatusAndInt(status, value)) {
mRdsPTY = (Integer) value;
}
break;
case IFMCommand.FM_CMD_RDS_RTPLUS_AVAILABLE:
if (FMRadioUtil.checkStatusAndStr(status, value)) {
mRdsRTPlus = (String) value;
}
break;
case IFMCommand.FM_CMD_ENABLE_COMPLETE:
mIsEnable = true;
break;
case IFMCommand.FM_CMD_DISABLE_COMPLETE:
mPowerOffComplete = true;
break;
case IFMCommand.FM_CMD_ENABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = true;
}
break;
case IFMCommand.FM_CMD_DISABLE_RDS_DONE:
if (FMRadioUtil.checkStatus(status)) {
mRdsEnabled = false;
}
break;
}
if (mBeginInvokeCB) {
if (!mIgnoreCallBack) {
invokeCallback(cmd, status, value);
} else {
mIgnoreCallBack = false;
}
} else {
if (cmd == IFMCommand.FM_CMD_TUNE_COMPLETE || cmd == IFMCommand.FM_CMD_ENABLE_COMPLETE
|| cmd == IFMCommand.FM_CMD_SET_BAND_DONE || cmd == IFMCommand.FM_CMD_SET_RSSI_DONE) {
CBEntity cb = new CBEntity(cmd, status, value);
mCBList.add(cb);
}
if (enableCompleted(mCBList)) {
mBeginInvokeCB = true;
CBEntity cbEnable = getCBForEnable(mCBList);
if (cbEnable != null) {
invokeCallback(cbEnable.cmd, cbEnable.status, cbEnable.value);
}
CBEntity cbTune = getCBForTune(mCBList);
if (cbTune != null) {
invokeCallback(cbTune.cmd, cbTune.status, cbTune.value);
}
mCBList.clear();
}
}
}
|
diff --git a/src/ant/org/apache/hadoop/ant/condition/DfsBaseConditional.java b/src/ant/org/apache/hadoop/ant/condition/DfsBaseConditional.java
index 3c69c5c15..33cf52b1c 100644
--- a/src/ant/org/apache/hadoop/ant/condition/DfsBaseConditional.java
+++ b/src/ant/org/apache/hadoop/ant/condition/DfsBaseConditional.java
@@ -1,68 +1,68 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ant.condition;
import org.apache.tools.ant.taskdefs.condition.Condition;
/**
* This wrapper around {@link org.apache.hadoop.ant.DfsTask} implements the
* Ant >1.5
* {@link org.apache.tools.ant.taskdefs.condition.Condition Condition}
* interface for HDFS tests. So one can test conditions like this:
* {@code
* <condition property="precond">
* <and>
* <hadoop:exists file="fileA" />
* <hadoop:exists file="fileB" />
* <hadoop:sizezero file="fileB" />
* </and>
* </condition>
* }
* This will define the property precond if fileA exists and fileB has zero
* length.
*/
public abstract class DfsBaseConditional extends org.apache.hadoop.ant.DfsTask
implements Condition {
protected boolean result;
String file;
private void initArgs() {
setCmd("test");
setArgs("-" + getFlag() + "," + file);
}
public void setFile(String file) {
this.file = file;
}
protected abstract char getFlag();
protected int postCmd(int exit_code) {
exit_code = super.postCmd(exit_code);
- result = exit_code == 1;
+ result = exit_code == 0;
return exit_code;
}
public boolean eval() {
initArgs();
execute();
return result;
}
}
| true | true | protected int postCmd(int exit_code) {
exit_code = super.postCmd(exit_code);
result = exit_code == 1;
return exit_code;
}
| protected int postCmd(int exit_code) {
exit_code = super.postCmd(exit_code);
result = exit_code == 0;
return exit_code;
}
|
diff --git a/src/main/java/org/structnetalign/cross/SimpleCrossingManager.java b/src/main/java/org/structnetalign/cross/SimpleCrossingManager.java
index eb596b9..d0814bb 100644
--- a/src/main/java/org/structnetalign/cross/SimpleCrossingManager.java
+++ b/src/main/java/org/structnetalign/cross/SimpleCrossingManager.java
@@ -1,154 +1,154 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* @author dmyersturnbull
*/
package org.structnetalign.cross;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.structnetalign.CleverGraph;
import org.structnetalign.InteractionEdge;
import org.structnetalign.PipelineProperties;
import org.structnetalign.ReportGenerator;
import org.structnetalign.util.GraphMLAdaptor;
import org.xml.sax.SAXException;
public class SimpleCrossingManager implements CrossingManager {
private static final Logger logger = LogManager.getLogger("org.structnetalign");
private int maxDepth;
private int nCores;
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
if (args.length != 3) {
System.err.println("Usage: " + SimpleCrossingManager.class.getSimpleName() + " interaction-graph-file homology-graph-file output-file");
return;
}
File interactionFile = new File(args[0]);
File homologyFile = new File(args[1]);
File output = new File(args[2]);
CleverGraph graph = GraphMLAdaptor.readGraph(interactionFile, homologyFile);
SimpleCrossingManager cross = new SimpleCrossingManager(2, 1000);
cross.cross(graph);
GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), output);
}
public SimpleCrossingManager(int nCores, int maxDepth) {
this.nCores = nCores;
this.maxDepth = maxDepth;
}
@Override
public void cross(CleverGraph graph) {
ExecutorService pool = Executors.newFixedThreadPool(nCores);
try {
// depressingly, this used to be List<Future<Pair<Map<Integer,Double>>>>
// I'm glad that's no longer the case
CompletionService<InteractionEdgeUpdate> completion = new ExecutorCompletionService<>(pool);
List<Future<InteractionEdgeUpdate>> futures = new ArrayList<>();
// submit the jobs
for (InteractionEdge interaction : graph.getInteraction().getEdges()) {
HomologySearchJob job = new HomologySearchJob(interaction, graph);
job.setMaxDepth(maxDepth);
Future<InteractionEdgeUpdate> result = completion.submit(job);
futures.add(result);
}
/*
* We'll make a list of updates to do when we're finished.
* Otherwise, we can run into some ugly concurrency issues and get the wrong answer.
*/
int nUpdates = 0;
int nEdgesUpdated = 0;
WeakHashMap<InteractionEdge, Double> edgesToUpdate = new WeakHashMap<>(futures.size());
for (Future<InteractionEdgeUpdate> future : futures) {
// now wait for completion
InteractionEdgeUpdate update = null;
try {
// We should do this in case the job gets interrupted
// Sometimes the OS or JVM might do this
// Use the flag instead of future == null because future.get() may actually return null
while (update == null) {
try {
update = future.get();
} catch (InterruptedException e) {
logger.warn("A thread was interrupted while waiting to get interaction udpate. Retrying.", e);
continue;
}
}
} catch (ExecutionException e) {
logger.error("Encountered an error trying to update an interaction. Skipping interaction.", e);
continue;
}
// we have an update to make!
nUpdates += update.getnUpdates();
- if (nUpdates > 0) { // don't bother if we didn't change anything
+ if (update.getnUpdates() > 0) { // don't bother if we didn't change anything
nEdgesUpdated++;
InteractionEdge edge = update.getRootInteraction(); // don't make a copy here!!
edgesToUpdate.put(edge, edge.getWeight() + update.getScore() - edge.getWeight() * update.getScore());
logger.debug("Updated interaction " + edge.getId() + " to " + PipelineProperties.getInstance().getDisplayFormatter().format(edge.getWeight()));
}
}
/*
* Now that the multithreaded part has finished, we can update the interactions.
*/
for (InteractionEdge edge : edgesToUpdate.keySet()) {
edge.setWeight(edgesToUpdate.get(edge));
}
if (ReportGenerator.getInstance() != null) {
ReportGenerator.getInstance().putInCrossed("manager", this.getClass().getSimpleName());
ReportGenerator.getInstance().putInCrossed("n_updates", nUpdates);
ReportGenerator.getInstance().putInCrossed("n_updated", nEdgesUpdated);
}
} finally {
pool.shutdownNow();
int count = Thread.activeCount()-1;
if (count > 0) {
logger.warn("There are " + count + " lingering threads");
}
}
}
}
| true | true | public void cross(CleverGraph graph) {
ExecutorService pool = Executors.newFixedThreadPool(nCores);
try {
// depressingly, this used to be List<Future<Pair<Map<Integer,Double>>>>
// I'm glad that's no longer the case
CompletionService<InteractionEdgeUpdate> completion = new ExecutorCompletionService<>(pool);
List<Future<InteractionEdgeUpdate>> futures = new ArrayList<>();
// submit the jobs
for (InteractionEdge interaction : graph.getInteraction().getEdges()) {
HomologySearchJob job = new HomologySearchJob(interaction, graph);
job.setMaxDepth(maxDepth);
Future<InteractionEdgeUpdate> result = completion.submit(job);
futures.add(result);
}
/*
* We'll make a list of updates to do when we're finished.
* Otherwise, we can run into some ugly concurrency issues and get the wrong answer.
*/
int nUpdates = 0;
int nEdgesUpdated = 0;
WeakHashMap<InteractionEdge, Double> edgesToUpdate = new WeakHashMap<>(futures.size());
for (Future<InteractionEdgeUpdate> future : futures) {
// now wait for completion
InteractionEdgeUpdate update = null;
try {
// We should do this in case the job gets interrupted
// Sometimes the OS or JVM might do this
// Use the flag instead of future == null because future.get() may actually return null
while (update == null) {
try {
update = future.get();
} catch (InterruptedException e) {
logger.warn("A thread was interrupted while waiting to get interaction udpate. Retrying.", e);
continue;
}
}
} catch (ExecutionException e) {
logger.error("Encountered an error trying to update an interaction. Skipping interaction.", e);
continue;
}
// we have an update to make!
nUpdates += update.getnUpdates();
if (nUpdates > 0) { // don't bother if we didn't change anything
nEdgesUpdated++;
InteractionEdge edge = update.getRootInteraction(); // don't make a copy here!!
edgesToUpdate.put(edge, edge.getWeight() + update.getScore() - edge.getWeight() * update.getScore());
logger.debug("Updated interaction " + edge.getId() + " to " + PipelineProperties.getInstance().getDisplayFormatter().format(edge.getWeight()));
}
}
/*
* Now that the multithreaded part has finished, we can update the interactions.
*/
for (InteractionEdge edge : edgesToUpdate.keySet()) {
edge.setWeight(edgesToUpdate.get(edge));
}
if (ReportGenerator.getInstance() != null) {
ReportGenerator.getInstance().putInCrossed("manager", this.getClass().getSimpleName());
ReportGenerator.getInstance().putInCrossed("n_updates", nUpdates);
ReportGenerator.getInstance().putInCrossed("n_updated", nEdgesUpdated);
}
} finally {
pool.shutdownNow();
int count = Thread.activeCount()-1;
if (count > 0) {
logger.warn("There are " + count + " lingering threads");
}
}
}
| public void cross(CleverGraph graph) {
ExecutorService pool = Executors.newFixedThreadPool(nCores);
try {
// depressingly, this used to be List<Future<Pair<Map<Integer,Double>>>>
// I'm glad that's no longer the case
CompletionService<InteractionEdgeUpdate> completion = new ExecutorCompletionService<>(pool);
List<Future<InteractionEdgeUpdate>> futures = new ArrayList<>();
// submit the jobs
for (InteractionEdge interaction : graph.getInteraction().getEdges()) {
HomologySearchJob job = new HomologySearchJob(interaction, graph);
job.setMaxDepth(maxDepth);
Future<InteractionEdgeUpdate> result = completion.submit(job);
futures.add(result);
}
/*
* We'll make a list of updates to do when we're finished.
* Otherwise, we can run into some ugly concurrency issues and get the wrong answer.
*/
int nUpdates = 0;
int nEdgesUpdated = 0;
WeakHashMap<InteractionEdge, Double> edgesToUpdate = new WeakHashMap<>(futures.size());
for (Future<InteractionEdgeUpdate> future : futures) {
// now wait for completion
InteractionEdgeUpdate update = null;
try {
// We should do this in case the job gets interrupted
// Sometimes the OS or JVM might do this
// Use the flag instead of future == null because future.get() may actually return null
while (update == null) {
try {
update = future.get();
} catch (InterruptedException e) {
logger.warn("A thread was interrupted while waiting to get interaction udpate. Retrying.", e);
continue;
}
}
} catch (ExecutionException e) {
logger.error("Encountered an error trying to update an interaction. Skipping interaction.", e);
continue;
}
// we have an update to make!
nUpdates += update.getnUpdates();
if (update.getnUpdates() > 0) { // don't bother if we didn't change anything
nEdgesUpdated++;
InteractionEdge edge = update.getRootInteraction(); // don't make a copy here!!
edgesToUpdate.put(edge, edge.getWeight() + update.getScore() - edge.getWeight() * update.getScore());
logger.debug("Updated interaction " + edge.getId() + " to " + PipelineProperties.getInstance().getDisplayFormatter().format(edge.getWeight()));
}
}
/*
* Now that the multithreaded part has finished, we can update the interactions.
*/
for (InteractionEdge edge : edgesToUpdate.keySet()) {
edge.setWeight(edgesToUpdate.get(edge));
}
if (ReportGenerator.getInstance() != null) {
ReportGenerator.getInstance().putInCrossed("manager", this.getClass().getSimpleName());
ReportGenerator.getInstance().putInCrossed("n_updates", nUpdates);
ReportGenerator.getInstance().putInCrossed("n_updated", nEdgesUpdated);
}
} finally {
pool.shutdownNow();
int count = Thread.activeCount()-1;
if (count > 0) {
logger.warn("There are " + count + " lingering threads");
}
}
}
|
diff --git a/ide/eclipse/dependencies/maven-bpel-plugin/src/main/java/org/wso2/maven/bpel/artifact/BPELMojo.java b/ide/eclipse/dependencies/maven-bpel-plugin/src/main/java/org/wso2/maven/bpel/artifact/BPELMojo.java
index 841ea4bb7..9a7d03cd3 100644
--- a/ide/eclipse/dependencies/maven-bpel-plugin/src/main/java/org/wso2/maven/bpel/artifact/BPELMojo.java
+++ b/ide/eclipse/dependencies/maven-bpel-plugin/src/main/java/org/wso2/maven/bpel/artifact/BPELMojo.java
@@ -1,110 +1,110 @@
package org.wso2.maven.bpel.artifact;
import java.io.File;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.wso2.maven.bpel.artifact.utils.FileUtils;
/**
* Create a bpel artifact from Maven project
*
* @goal bpel
* @phase package
* @description build an bpel artifact
*/
public class BPELMojo extends AbstractMojo {
/**
* @parameter default-value="${project.basedir}"
*/
private File path;
/**
* @parameter default-value="zip"
*/
private String type;
/**
* @parameter default-value="false"
*/
private boolean enableArchive;
/**
* @parameter default-value="${project}"
*/
private MavenProject mavenProject;
/**
* Maven ProjectHelper.
*
* @component
*/
private MavenProjectHelper projectHelper;
public void execute() throws MojoExecutionException, MojoFailureException {
File project = path;
try {
createZip(project);
} catch (Exception e) {
e.printStackTrace();
}
}
public void createZip(File project) throws MojoExecutionException {
try {
String bpelArtifactFullPath = getBPELProjectName(project);
File bpelArtifactFile = new File(bpelArtifactFullPath);
String artifactType = getType();
- String artifactName=mavenProject.getArtifactId()+"."+artifactType;
+ String artifactName=mavenProject.getArtifactId() + "-" + mavenProject.getVersion() + "." + artifactType;
File archive = FileUtils.createArchive(project, bpelArtifactFile, artifactName);
if (archive != null && archive.exists()) {
mavenProject.getArtifact().setFile(archive);
} else {
throw new MojoExecutionException(archive + " is null or doesn't exist");
}
} catch (Exception e) {
throw new MojoExecutionException("Error while creating bpel archive",e);
}
}
public String getBPELProjectName(File project) {
List<File> fileList = FileUtils.getAllFilesPresentInFolder(project);
String bpelProjectName = project.getName();
for (int i = 0; i < fileList.size(); i++) {
File file = fileList.get(i);
if (!file.isDirectory()) {
try {
if (file.getName().toLowerCase().endsWith(".bpel")) {
bpelProjectName = file.getParent();
return bpelProjectName;
}
} catch (Exception e) {
}
}
}
return bpelProjectName;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setEnableArchive(boolean enableArchive) {
this.enableArchive = enableArchive;
}
public boolean isEnableArchive() {
return enableArchive;
}
}
| true | true | public void createZip(File project) throws MojoExecutionException {
try {
String bpelArtifactFullPath = getBPELProjectName(project);
File bpelArtifactFile = new File(bpelArtifactFullPath);
String artifactType = getType();
String artifactName=mavenProject.getArtifactId()+"."+artifactType;
File archive = FileUtils.createArchive(project, bpelArtifactFile, artifactName);
if (archive != null && archive.exists()) {
mavenProject.getArtifact().setFile(archive);
} else {
throw new MojoExecutionException(archive + " is null or doesn't exist");
}
} catch (Exception e) {
throw new MojoExecutionException("Error while creating bpel archive",e);
}
}
| public void createZip(File project) throws MojoExecutionException {
try {
String bpelArtifactFullPath = getBPELProjectName(project);
File bpelArtifactFile = new File(bpelArtifactFullPath);
String artifactType = getType();
String artifactName=mavenProject.getArtifactId() + "-" + mavenProject.getVersion() + "." + artifactType;
File archive = FileUtils.createArchive(project, bpelArtifactFile, artifactName);
if (archive != null && archive.exists()) {
mavenProject.getArtifact().setFile(archive);
} else {
throw new MojoExecutionException(archive + " is null or doesn't exist");
}
} catch (Exception e) {
throw new MojoExecutionException("Error while creating bpel archive",e);
}
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/main/RecognizedOptions.java b/src/share/classes/com/sun/tools/javafx/main/RecognizedOptions.java
index 342ce887b..7d0608a95 100644
--- a/src/share/classes/com/sun/tools/javafx/main/RecognizedOptions.java
+++ b/src/share/classes/com/sun/tools/javafx/main/RecognizedOptions.java
@@ -1,595 +1,594 @@
/*
* Copyright 1999-2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.main;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javafx.main.JavafxOption.HiddenOption;
import com.sun.tools.javafx.main.JavafxOption.Option;
import com.sun.tools.javafx.main.JavafxOption.XOption;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Options;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.EnumSet;
import java.util.Set;
import java.util.StringTokenizer;
import javax.lang.model.SourceVersion;
import static com.sun.tools.javafx.main.OptionName.*;
/**
* TODO: describe com.sun.tools.javac.main.RecognizedOptions
*
* <p><b>This is NOT part of any API supported by Sun Microsystems.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class RecognizedOptions {
private RecognizedOptions() {}
public interface OptionHelper {
void setOut(PrintWriter out);
void error(String key, Object... args);
void printVersion();
void printFullVersion();
void printHelp();
void printXhelp();
void addFile(File f);
void addClassName(String s);
}
public static class GrumpyHelper implements OptionHelper {
public void setOut(PrintWriter out) {
throw new IllegalArgumentException();
}
public void error(String key, Object... args) {
throw new IllegalArgumentException(Main.getLocalizedString(key, args));
}
public void printVersion() {
throw new IllegalArgumentException();
}
public void printFullVersion() {
throw new IllegalArgumentException();
}
public void printHelp() {
throw new IllegalArgumentException();
}
public void printXhelp() {
throw new IllegalArgumentException();
}
public void addFile(File f) {
throw new IllegalArgumentException(f.getPath());
}
public void addClassName(String s) {
throw new IllegalArgumentException(s);
}
}
static Set<OptionName> javafxcOptions = EnumSet.of(
G,
G_NONE,
G_CUSTOM,
XLINT,
XLINT_CUSTOM,
NOWARN,
VERBOSE,
DEPRECATION,
CLASSPATH,
CP,
SOURCEPATH,
BOOTCLASSPATH,
XBOOTCLASSPATH_PREPEND,
XBOOTCLASSPATH_APPEND,
XBOOTCLASSPATH,
EXTDIRS,
DJAVA_EXT_DIRS,
ENDORSEDDIRS,
DJAVA_ENDORSED_DIRS,
PROC_CUSTOM,
PROCESSOR,
PROCESSORPATH,
D,
S,
IMPLICIT,
ENCODING,
SOURCE,
TARGET,
PLATFORM,
VERSION,
FULLVERSION,
HELP,
A,
X,
J,
MOREINFO,
WERROR,
// COMPLEXINFERENCE,
PROMPT,
DOE,
PRINTSOURCE,
WARNUNCHECKED,
XMAXERRS,
XMAXWARNS,
XSTDOUT,
XPRINT,
XPRINTROUNDS,
XPRINTPROCESSORINFO,
XPREFER,
O,
XJCOV,
XD,
DUMPJAVA,
DUMPFX,
SOURCEFILE);
static Set<OptionName> javacFileManagerOptions = EnumSet.of(
CLASSPATH,
CP,
SOURCEPATH,
BOOTCLASSPATH,
XBOOTCLASSPATH_PREPEND,
XBOOTCLASSPATH_APPEND,
XBOOTCLASSPATH,
EXTDIRS,
DJAVA_EXT_DIRS,
ENDORSEDDIRS,
DJAVA_ENDORSED_DIRS,
PROCESSORPATH,
D,
S,
ENCODING,
SOURCE);
static Set<OptionName> javacToolOptions = EnumSet.of(
G,
G_NONE,
G_CUSTOM,
XLINT,
XLINT_CUSTOM,
NOWARN,
VERBOSE,
DEPRECATION,
PROC_CUSTOM,
PROCESSOR,
IMPLICIT,
SOURCE,
TARGET,
// VERSION,
// FULLVERSION,
// HELP,
A,
// X,
// J,
MOREINFO,
WERROR,
// COMPLEXINFERENCE,
PROMPT,
DOE,
PRINTSOURCE,
WARNUNCHECKED,
XMAXERRS,
XMAXWARNS,
// XSTDOUT,
XPRINT,
XPRINTROUNDS,
XPRINTPROCESSORINFO,
XPREFER,
O,
XJCOV,
XD);
static Option[] getJavaCompilerOptions(OptionHelper helper) {
return getOptions(helper, javafxcOptions);
}
public static Option[] getJavacFileManagerOptions(OptionHelper helper) {
return getOptions(helper, javacFileManagerOptions);
}
public static Option[] getJavacToolOptions(OptionHelper helper) {
return getOptions(helper, javacToolOptions);
}
static Option[] getOptions(OptionHelper helper, Set<OptionName> desired) {
ListBuffer<Option> options = new ListBuffer<Option>();
for (Option option : getAll(helper))
if (desired.contains(option.getName()))
options.append(option);
return options.toArray(new Option[options.length()]);
}
/**
* @param out the writer to use for diagnostic output
*/
public static Option[] getAll(final OptionHelper helper) {
return new Option[]{
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source") {
public boolean matches(String s) {
return s.startsWith("-g:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(3);
options.put("-g:", suboptions);
// enter all the -g suboptions as "-g:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-g:" + tok;
options.put(opt, opt);
}
return false;
}
},
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-Xlint:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(7);
options.put("-Xlint:", suboptions);
// enter all the -Xlint suboptions as "-Xlint:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-Xlint:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"),
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC_CUSTOM, "opt.proc.none.only") {
public boolean matches(String s) {
return s.equals("-proc:none") || s.equals("-proc:only");
}
public boolean process(Options options, String option) {
if (option.equals("-proc:none")) {
options.remove("-proc:only");
} else {
options.remove("-proc:none");
}
options.put(option, option);
return false;
}
},
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit") {
public boolean matches(String s) {
return s.equals("-implicit:none") || s.equals("-implicit:class");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
new Option(ENCODING, "opt.arg.encoding", "opt.encoding"),
new Option(SOURCE, "opt.arg.release", "opt.source") {
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new JavafxOption.FXOption(PLATFORM, "javafx.opt.arg.name", "javafx.opt.platform") {
},
new Option(VERSION, "opt.version") {
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new Option(HELP, "opt.help") {
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(X, "opt.X") {
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new HiddenOption(WERROR),
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer") {
public boolean matches(String s) {
return s.equals("-Xprefer:source") || s.equals("-Xprefer:newer");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// Javafxc-specific options
new HiddenOption(DUMPJAVA),
new HiddenOption(DUMPFX),
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candiate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
public boolean matches(String s) {
this.s = s;
- return s.endsWith(".fx") // Java source file
- || SourceVersion.isName(s); // Legal type name
+ return s.endsWith(".fx"); // Javafx source file
}
public boolean process(Options options, String option) {
if (s.endsWith(".fx") ) {
File f = new File(s);
if (!f.exists()) {
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else
helper.addClassName(s);
return false;
}
},
};
}
}
| true | true | public static Option[] getAll(final OptionHelper helper) {
return new Option[]{
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source") {
public boolean matches(String s) {
return s.startsWith("-g:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(3);
options.put("-g:", suboptions);
// enter all the -g suboptions as "-g:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-g:" + tok;
options.put(opt, opt);
}
return false;
}
},
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-Xlint:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(7);
options.put("-Xlint:", suboptions);
// enter all the -Xlint suboptions as "-Xlint:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-Xlint:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"),
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC_CUSTOM, "opt.proc.none.only") {
public boolean matches(String s) {
return s.equals("-proc:none") || s.equals("-proc:only");
}
public boolean process(Options options, String option) {
if (option.equals("-proc:none")) {
options.remove("-proc:only");
} else {
options.remove("-proc:none");
}
options.put(option, option);
return false;
}
},
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit") {
public boolean matches(String s) {
return s.equals("-implicit:none") || s.equals("-implicit:class");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
new Option(ENCODING, "opt.arg.encoding", "opt.encoding"),
new Option(SOURCE, "opt.arg.release", "opt.source") {
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new JavafxOption.FXOption(PLATFORM, "javafx.opt.arg.name", "javafx.opt.platform") {
},
new Option(VERSION, "opt.version") {
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new Option(HELP, "opt.help") {
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(X, "opt.X") {
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new HiddenOption(WERROR),
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer") {
public boolean matches(String s) {
return s.equals("-Xprefer:source") || s.equals("-Xprefer:newer");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// Javafxc-specific options
new HiddenOption(DUMPJAVA),
new HiddenOption(DUMPFX),
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candiate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
public boolean matches(String s) {
this.s = s;
return s.endsWith(".fx") // Java source file
|| SourceVersion.isName(s); // Legal type name
}
public boolean process(Options options, String option) {
if (s.endsWith(".fx") ) {
File f = new File(s);
if (!f.exists()) {
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else
helper.addClassName(s);
return false;
}
},
};
}
| public static Option[] getAll(final OptionHelper helper) {
return new Option[]{
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source") {
public boolean matches(String s) {
return s.startsWith("-g:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(3);
options.put("-g:", suboptions);
// enter all the -g suboptions as "-g:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-g:" + tok;
options.put(opt, opt);
}
return false;
}
},
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-Xlint:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(7);
options.put("-Xlint:", suboptions);
// enter all the -Xlint suboptions as "-Xlint:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-Xlint:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"),
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC_CUSTOM, "opt.proc.none.only") {
public boolean matches(String s) {
return s.equals("-proc:none") || s.equals("-proc:only");
}
public boolean process(Options options, String option) {
if (option.equals("-proc:none")) {
options.remove("-proc:only");
} else {
options.remove("-proc:none");
}
options.put(option, option);
return false;
}
},
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit") {
public boolean matches(String s) {
return s.equals("-implicit:none") || s.equals("-implicit:class");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
new Option(ENCODING, "opt.arg.encoding", "opt.encoding"),
new Option(SOURCE, "opt.arg.release", "opt.source") {
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new JavafxOption.FXOption(PLATFORM, "javafx.opt.arg.name", "javafx.opt.platform") {
},
new Option(VERSION, "opt.version") {
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new Option(HELP, "opt.help") {
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(X, "opt.X") {
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new HiddenOption(WERROR),
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer") {
public boolean matches(String s) {
return s.equals("-Xprefer:source") || s.equals("-Xprefer:newer");
}
public boolean process(Options options, String option, String operand) {
int sep = option.indexOf(":");
options.put(option.substring(0, sep), option.substring(sep+1));
options.put(option,option);
return false;
}
},
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// Javafxc-specific options
new HiddenOption(DUMPJAVA),
new HiddenOption(DUMPFX),
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candiate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
public boolean matches(String s) {
this.s = s;
return s.endsWith(".fx"); // Javafx source file
}
public boolean process(Options options, String option) {
if (s.endsWith(".fx") ) {
File f = new File(s);
if (!f.exists()) {
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else
helper.addClassName(s);
return false;
}
},
};
}
|
diff --git a/misc/src/main/java/struct/recur/BinaryTree.java b/misc/src/main/java/struct/recur/BinaryTree.java
index 9b1a8c8..208b23b 100644
--- a/misc/src/main/java/struct/recur/BinaryTree.java
+++ b/misc/src/main/java/struct/recur/BinaryTree.java
@@ -1,236 +1,236 @@
package struct.recur;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import struct.AbsTree;
public class BinaryTree implements AbsTree {
public static enum TraverseType {
PRE_ORDER, IN_ORDER, POST_ORDER,
}
public static class BinaryTreeNode {
private Object data;
private BinaryTreeNode left;
private BinaryTreeNode right;
private BinaryTreeNode parent;
}
private List<BinaryTreeNode> nodeList = new LinkedList<BinaryTreeNode>();
public static void traverse_recurPreOrder(BinaryTreeNode node,
List<Object> data) {
data.add(node.data);
if (node.left != null) {
traverse_recurPreOrder(node.left, data);
}
if (node.right != null) {
traverse_recurPreOrder(node.right, data);
}
}
public static void traverse_recurInOrder(BinaryTreeNode node,
List<Object> data) {
if (node.left != null) {
traverse_recurInOrder(node.left, data);
}
data.add(node.data);
if (node.right != null) {
traverse_recurInOrder(node.right, data);
}
}
public static void traverse_recurPostOrder(BinaryTreeNode node,
List<Object> data) {
if (node.left != null) {
traverse_recurPostOrder(node.left, data);
}
if (node.right != null) {
traverse_recurPostOrder(node.right, data);
}
data.add(node.data);
}
private static int findIndex(List<Object> list, Object key) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == key) {
return i;
}
}
System.out.println("Failed to find the element " + key);
return -1;
}
public static BinaryTreeNode createTree_recur(List<Object> preOrder,
List<Object> inOrder) {
BinaryTreeNode _root = null;
// The head of the preOrder if the root node
_root = new BinaryTreeNode();
_root.data = preOrder.get(0);
// The all elements in the inOrder before the root is the left tree
int _rootIndex = findIndex(inOrder, _root.data);
int _leftTreeLen = _rootIndex;
int _rightTreeLen = inOrder.size() - _leftTreeLen - 1;
if (_leftTreeLen > 0) {
_root.left = createTree_recur(
preOrder.subList(1, _leftTreeLen + 1),
inOrder.subList(0, _leftTreeLen));
_root.left.parent = _root;
}
if (_rightTreeLen > 0) {
_root.right = createTree_recur(
preOrder.subList(_leftTreeLen + 1, preOrder.size()),
inOrder.subList(_leftTreeLen + 1, inOrder.size()));
_root.right.parent = _root;
}
return _root;
}
public static int getDegree() {
return 0;
}
public static void traversePreOrder(BinaryTreeNode head, List<Object> data) {
// Push the root node
Stack<BinaryTreeNode> _nodeStack = new Stack<BinaryTreeNode>();
_nodeStack.push(head);
while (!_nodeStack.isEmpty()) {
// Push the left tree
while (_nodeStack.lastElement() != null) {
data.add(_nodeStack.lastElement().data);
_nodeStack.push(_nodeStack.lastElement().left);
}
// The top the stack should be null(_nodeStack.lastElement().left)
// That is useful to prevent enter the previous loop
// Now, pop it
_nodeStack.pop();
if (!_nodeStack.isEmpty()) {
// The root is useless to traverse the right tree, pop it and
// goon
BinaryTreeNode _tmp = _nodeStack.pop();
_nodeStack.push(_tmp.right);
}
}
}
public static void traverseInOrder(BinaryTreeNode head, List<Object> data) {
// Push the root node
Stack<BinaryTreeNode> _nodeStack = new Stack<BinaryTreeNode>();
_nodeStack.push(head);
while (!_nodeStack.isEmpty()) {
// Push the left tree
while (_nodeStack.lastElement() != null) {
_nodeStack.push(_nodeStack.lastElement().left);
}
// The top the stack should be null(_nodeStack.lastElement().left)
// That is useful to prevent enter the previous loop
// Now, pop it
_nodeStack.pop();
if (!_nodeStack.isEmpty()) {
// The root is useless to traverse the right tree, pop it and
// goon
BinaryTreeNode _tmp = _nodeStack.pop();
_nodeStack.push(_tmp.right);
data.add(_tmp.data);
}
}
}
public static int getDepth(BinaryTreeNode head) {
int _leftDepth = 0;
int _maxDepth = 0;
Stack<BinaryTreeNode> _nodeStack = new Stack<BinaryTreeNode>();
BinaryTreeNode _tmp = head;
_nodeStack.push(_tmp);
System.out.println(_tmp.data);
_leftDepth++;
while (!_nodeStack.isEmpty()) {
_tmp = _nodeStack.lastElement();
// Push the left tree
while (_tmp.left != null) {
_tmp = _tmp.left;
- visit(_tmp);
+ // visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
}
// Pop self
_nodeStack.pop();
// Push the right tree
if (!_nodeStack.isEmpty()) {
// Pop the parent
_tmp = _nodeStack.pop();
if (_tmp.right != null) {
_tmp = _tmp.right;
- visit(_tmp);
+ // visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
} else {
if (!_nodeStack.isEmpty()) {
_nodeStack.pop();
if (_maxDepth < _leftDepth) {
_maxDepth = _leftDepth;
}
_leftDepth--;
}
}
}
}
return _maxDepth;
}
public static int getDepth_recur(BinaryTreeNode node) {
int _maxDepth = 0;
int _depth = 1;
int _leftDepth = 0;
int _rightDepth = 0;
if (node.left != null) {
_leftDepth = getDepth_recur(node.left);
}
if (node.right != null) {
_rightDepth = getDepth_recur(node.right);
}
_depth += Math.max(_leftDepth, _rightDepth);
if (_depth > _maxDepth) {
_maxDepth = _depth;
}
return _maxDepth;
}
public static int getNodeCount_recur(BinaryTreeNode node) {
int _result = 0;
_result++;
if (node.left != null) {
_result += getNodeCount_recur(node.left);
}
if (node.right != null) {
_result += getNodeCount_recur(node.right);
}
return _result;
}
public boolean isEmpty() {
return nodeList.isEmpty();
}
}
| false | true | public static int getDepth(BinaryTreeNode head) {
int _leftDepth = 0;
int _maxDepth = 0;
Stack<BinaryTreeNode> _nodeStack = new Stack<BinaryTreeNode>();
BinaryTreeNode _tmp = head;
_nodeStack.push(_tmp);
System.out.println(_tmp.data);
_leftDepth++;
while (!_nodeStack.isEmpty()) {
_tmp = _nodeStack.lastElement();
// Push the left tree
while (_tmp.left != null) {
_tmp = _tmp.left;
visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
}
// Pop self
_nodeStack.pop();
// Push the right tree
if (!_nodeStack.isEmpty()) {
// Pop the parent
_tmp = _nodeStack.pop();
if (_tmp.right != null) {
_tmp = _tmp.right;
visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
} else {
if (!_nodeStack.isEmpty()) {
_nodeStack.pop();
if (_maxDepth < _leftDepth) {
_maxDepth = _leftDepth;
}
_leftDepth--;
}
}
}
}
return _maxDepth;
}
| public static int getDepth(BinaryTreeNode head) {
int _leftDepth = 0;
int _maxDepth = 0;
Stack<BinaryTreeNode> _nodeStack = new Stack<BinaryTreeNode>();
BinaryTreeNode _tmp = head;
_nodeStack.push(_tmp);
System.out.println(_tmp.data);
_leftDepth++;
while (!_nodeStack.isEmpty()) {
_tmp = _nodeStack.lastElement();
// Push the left tree
while (_tmp.left != null) {
_tmp = _tmp.left;
// visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
}
// Pop self
_nodeStack.pop();
// Push the right tree
if (!_nodeStack.isEmpty()) {
// Pop the parent
_tmp = _nodeStack.pop();
if (_tmp.right != null) {
_tmp = _tmp.right;
// visit(_tmp);
_nodeStack.push(_tmp);
_leftDepth++;
} else {
if (!_nodeStack.isEmpty()) {
_nodeStack.pop();
if (_maxDepth < _leftDepth) {
_maxDepth = _leftDepth;
}
_leftDepth--;
}
}
}
}
return _maxDepth;
}
|
diff --git a/CoreComponents/src/org/sleuthkit/autopsy/corecomponents/DataContentViewerMedia.java b/CoreComponents/src/org/sleuthkit/autopsy/corecomponents/DataContentViewerMedia.java
index 2ed1a3fdc..86b5e330c 100644
--- a/CoreComponents/src/org/sleuthkit/autopsy/corecomponents/DataContentViewerMedia.java
+++ b/CoreComponents/src/org/sleuthkit/autopsy/corecomponents/DataContentViewerMedia.java
@@ -1,526 +1,526 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.corecomponents;
import java.awt.Component;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.gstreamer.*;
import org.gstreamer.elements.PlayBin2;
import org.gstreamer.swing.VideoComponent;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.nodes.Node;
import org.openide.util.Cancellable;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataContentViewer;
import org.sleuthkit.autopsy.datamodel.ContentUtils;
import org.sleuthkit.datamodel.File;
import org.sleuthkit.datamodel.TskData;
/**
*
* @author dfickling
*/
@ServiceProvider(service = DataContentViewer.class, position = 5)
public class DataContentViewerMedia extends javax.swing.JPanel implements DataContentViewer {
private static final String[] IMAGES = new String[]{".jpg", ".jpeg", ".png", ".gif", ".jpe", ".bmp"};
private static final String[] VIDEOS = new String[]{".mov", ".m4v", ".flv", ".mp4", ".3gp", ".avi", ".mpg", ".mpeg"};
private static final String[] AUDIOS = new String[]{".mp3", ".wav", ".wma"};
private static final Logger logger = Logger.getLogger(DataContentViewerMedia.class.getName());
private VideoComponent videoComponent;
private PlayBin2 playbin2;
private File currentFile;
private long durationMillis = 0;
private boolean autoTracking = false; // true if the slider is moving automatically
private final Object playbinLock = new Object(); // lock for synchronization of playbin2 player
/**
* Creates new form DataContentViewerVideo
*/
public DataContentViewerMedia() {
initComponents();
customizeComponents();
}
private void customizeComponents() {
Gst.init();
progressSlider.addChangeListener(new ChangeListener() {
/**
* Should always try to synchronize any call to
* progressSlider.setValue() to avoid a different thread changing
* playbin while stateChanged() is processing
*/
@Override
public void stateChanged(ChangeEvent e) {
int time = progressSlider.getValue();
synchronized (playbinLock) {
if (playbin2 != null && !autoTracking) {
State orig = playbin2.getState();
playbin2.pause();
playbin2.seek(ClockTime.fromMillis(time));
playbin2.setState(orig);
}
}
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pauseButton = new javax.swing.JButton();
videoPanel = new javax.swing.JPanel();
progressSlider = new javax.swing.JSlider();
progressLabel = new javax.swing.JLabel();
pauseButton.setText(org.openide.util.NbBundle.getMessage(DataContentViewerMedia.class, "DataContentViewerMedia.pauseButton.text")); // NOI18N
pauseButton.setMaximumSize(new java.awt.Dimension(45, 23));
pauseButton.setMinimumSize(new java.awt.Dimension(45, 23));
pauseButton.setPreferredSize(new java.awt.Dimension(45, 23));
pauseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout videoPanelLayout = new javax.swing.GroupLayout(videoPanel);
videoPanel.setLayout(videoPanelLayout);
videoPanelLayout.setHorizontalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 283, Short.MAX_VALUE)
);
videoPanelLayout.setVerticalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 242, Short.MAX_VALUE)
);
progressSlider.setValue(0);
progressLabel.setText(org.openide.util.NbBundle.getMessage(DataContentViewerMedia.class, "DataContentViewerMedia.progressLabel.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(pauseButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(progressSlider, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(progressLabel)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(pauseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(progressSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(progressLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
}// </editor-fold>//GEN-END:initComponents
private void pauseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pauseButtonActionPerformed
synchronized (playbinLock) {
State state = playbin2.getState();
if (state.equals(State.PLAYING)) {
playbin2.pause();
pauseButton.setText("►");
playbin2.setState(State.PAUSED);
} else if (state.equals(State.PAUSED)) {
playbin2.play();
pauseButton.setText("||");
playbin2.setState(State.PLAYING);
} else if (state.equals(State.READY)) {
ExtractMedia em = new ExtractMedia(currentFile, getJFile(currentFile));
em.execute();
}
}
}//GEN-LAST:event_pauseButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton pauseButton;
private javax.swing.JLabel progressLabel;
private javax.swing.JSlider progressSlider;
private javax.swing.JPanel videoPanel;
// End of variables declaration//GEN-END:variables
@Override
public void setNode(Node selectedNode) {
reset();
setComponentsVisibility(false);
if (selectedNode == null) {
return;
}
File file = selectedNode.getLookup().lookup(File.class);
if (file == null) {
return;
}
currentFile = file;
if (containsExt(file.getName(), IMAGES)) {
showImage(file);
} else if (containsExt(file.getName(), VIDEOS) || containsExt(file.getName(), AUDIOS)) {
setupVideo(file);
}
}
/**
* Initialize vars and display the image on the panel.
*
* @param file
*/
private void showImage(File file) {
java.io.File ioFile = getJFile(file);
if (!ioFile.exists()) {
try {
ContentUtils.writeToFile(file, ioFile);
} catch (IOException ex) {
logger.log(Level.WARNING, "Error buffering file", ex);
}
}
videoComponent = new VideoComponent();
synchronized (playbinLock) {
playbin2 = new PlayBin2("ImageViewer");
playbin2.setVideoSink(videoComponent.getElement());
}
videoPanel.removeAll();
videoPanel.setLayout(new BoxLayout(videoPanel, BoxLayout.Y_AXIS));
videoPanel.add(videoComponent);
videoPanel.revalidate();
videoPanel.repaint();
synchronized (playbinLock) {
playbin2.setInputFile(ioFile);
playbin2.play();
}
videoPanel.setVisible(true);
}
/**
* Initialize all the necessary vars to play a video/audio file.
*
* @param file the File to play
*/
private void setupVideo(File file) {
java.io.File ioFile = getJFile(file);
pauseButton.setText("►");
progressSlider.setValue(0);
videoComponent = new VideoComponent();
synchronized (playbinLock) {
playbin2 = new PlayBin2("VideoPlayer");
playbin2.setVideoSink(videoComponent.getElement());
}
videoPanel.removeAll();
videoPanel.setLayout(new BoxLayout(videoPanel, BoxLayout.Y_AXIS));
videoPanel.add(videoComponent);
videoPanel.revalidate();
videoPanel.repaint();
synchronized (playbinLock) {
playbin2.setInputFile(ioFile);
playbin2.setState(State.READY);
}
setComponentsVisibility(true);
}
/**
* To set the visibility of specific components in this class.
*
* @param isVisible whether to show or hide the specific components
*/
private void setComponentsVisibility(boolean isVisible) {
pauseButton.setVisible(isVisible);
progressLabel.setVisible(isVisible);
progressSlider.setVisible(isVisible);
videoPanel.setVisible(isVisible);
}
@Override
public String getTitle() {
return "Media View";
}
@Override
public String getToolTip() {
return "Displays supported multimedia files";
}
@Override
public DataContentViewer getInstance() {
return new DataContentViewerMedia();
}
@Override
public Component getComponent() {
return this;
}
@Override
public void resetComponent() {
// we don't want this to do anything
// because we already reset on each selected node
}
private void reset() {
synchronized (playbinLock) {
if (playbin2 != null) {
if (playbin2.isPlaying()) {
playbin2.stop();
}
playbin2.setState(State.NULL);
// try {
// Thread.sleep(20); // gstreamer needs to catch up
// } catch (InterruptedException ex) { }
if (playbin2.getState().equals(State.NULL)) {
playbin2.dispose();
}
playbin2 = null;
}
videoComponent = null;
}
}
@Override
public boolean isSupported(Node node) {
if (node == null) {
return false;
}
File file = node.getLookup().lookup(File.class);
if (file == null) {
return false;
}
if (File.dirFlagToValue(file.getDir_flags()).equals(TskData.TSK_FS_NAME_FLAG_ENUM.TSK_FS_NAME_FLAG_UNALLOC.toString())) {
return false;
}
if (file.getSize() == 0) {
return false;
}
String name = file.getName().toLowerCase();
if (containsExt(name, IMAGES) || containsExt(name, AUDIOS) || containsExt(name, VIDEOS)) {
return true;
}
return false;
}
@Override
public int isPreferred(Node node, boolean isSupported) {
if (isSupported) {
return 7;
} else {
return 0;
}
}
private static boolean containsExt(String name, String[] exts) {
int extStart = name.lastIndexOf(".");
String ext = "";
if (extStart != -1) {
ext = name.substring(extStart, name.length()).toLowerCase();
}
return Arrays.asList(exts).contains(ext);
}
private java.io.File getJFile(File file) {
// Get the temp folder path of the case
String tempPath = Case.getCurrentCase().getTempDirectory();
String name = file.getName();
int extStart = name.lastIndexOf(".");
String ext = "";
if (extStart != -1) {
ext = name.substring(extStart, name.length()).toLowerCase();
}
tempPath = tempPath + java.io.File.separator + file.getId() + ext;
java.io.File tempFile = new java.io.File(tempPath);
return tempFile;
}
/* Thread that extracts and plays a file */
private class ExtractMedia extends SwingWorker<Object, Void> {
private ProgressHandle progress;
boolean success = false;
private File sFile;
private java.io.File jFile;
String duration;
String position;
ExtractMedia(org.sleuthkit.datamodel.File sFile, java.io.File jFile) {
this.sFile = sFile;
this.jFile = jFile;
}
;
@Override
protected Object doInBackground() throws Exception {
success = false;
progress = ProgressHandleFactory.createHandle("Buffering " + sFile.getName(), new Cancellable() {
@Override
public boolean cancel() {
return ExtractMedia.this.cancel(true);
}
});
progressLabel.setText("Buffering...");
progress.start();
progress.switchToDeterminate(100);
try {
ContentUtils.writeToFile(sFile, jFile, progress, this, true);
} catch (IOException ex) {
logger.log(Level.WARNING, "Error buffering file", ex);
}
success = true;
return null;
}
/* clean up or start the worker threads */
@Override
protected void done() {
try {
super.get(); //block and get all exceptions thrown while doInBackground()
} catch (CancellationException ex) {
logger.log(Level.INFO, "Media buffering was canceled.");
} catch (InterruptedException ex) {
logger.log(Level.INFO, "Media buffering was interrupted.");
} catch (Exception ex) {
logger.log(Level.SEVERE, "Fatal error during media buffering.", ex);
} finally {
progress.finish();
if (!this.isCancelled()) {
play();
}
}
}
private void play() {
if (jFile == null || !jFile.exists()) {
progressLabel.setText("Error buffering file");
return;
}
ClockTime dur = null;
synchronized (playbinLock) {
playbin2.play(); // must play, then pause and get state to get duration.
playbin2.pause();
playbin2.getState();
dur = playbin2.queryDuration();
}
duration = dur.toString();
durationMillis = dur.toMillis();
progressSlider.setMaximum((int) durationMillis);
progressSlider.setMinimum(0);
final String finalDuration;
if (duration.length() == 8 && duration.substring(0, 3).equals("00:")) {
finalDuration = duration.substring(3);
progressLabel.setText("00:00/" + duration);
} else {
finalDuration = duration;
progressLabel.setText("00:00:00/" + duration);
}
synchronized (playbinLock) {
playbin2.play();
}
pauseButton.setText("||");
new Thread(new Runnable() {
private boolean isPlayBinReady() {
synchronized (playbinLock) {
- return playbin2 != null && playbin2.getState().equals(State.NULL);
+ return playbin2 != null && !playbin2.getState().equals(State.NULL);
}
}
@Override
public void run() {
long positionMillis = 0;
while (positionMillis < durationMillis
&& isPlayBinReady() ) {
ClockTime pos = null;
synchronized (playbinLock) {
pos = playbin2.queryPosition();
}
position = pos.toString();
positionMillis = pos.toMillis();
if (position.length() == 8) {
position = position.substring(3);
}
progressLabel.setText(position + "/" + finalDuration);
autoTracking = true;
progressSlider.setValue((int) positionMillis);
autoTracking = false;
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
}
}
if (finalDuration.length() == 5) {
progressLabel.setText("00:00/" + finalDuration);
} else {
progressLabel.setText("00:00:00/" + finalDuration);
}
// If it reached the end
if (progressSlider.getValue() == progressSlider.getMaximum()) {
restartVideo();
}
}
public void restartVideo() {
synchronized (playbinLock) {
if (playbin2 != null) {
playbin2.stop();
playbin2.setState(State.READY); // ready to be played again
}
}
pauseButton.setText("►");
progressSlider.setValue(0);
}
}).start();
}
}
}
| true | true | private void play() {
if (jFile == null || !jFile.exists()) {
progressLabel.setText("Error buffering file");
return;
}
ClockTime dur = null;
synchronized (playbinLock) {
playbin2.play(); // must play, then pause and get state to get duration.
playbin2.pause();
playbin2.getState();
dur = playbin2.queryDuration();
}
duration = dur.toString();
durationMillis = dur.toMillis();
progressSlider.setMaximum((int) durationMillis);
progressSlider.setMinimum(0);
final String finalDuration;
if (duration.length() == 8 && duration.substring(0, 3).equals("00:")) {
finalDuration = duration.substring(3);
progressLabel.setText("00:00/" + duration);
} else {
finalDuration = duration;
progressLabel.setText("00:00:00/" + duration);
}
synchronized (playbinLock) {
playbin2.play();
}
pauseButton.setText("||");
new Thread(new Runnable() {
private boolean isPlayBinReady() {
synchronized (playbinLock) {
return playbin2 != null && playbin2.getState().equals(State.NULL);
}
}
@Override
public void run() {
long positionMillis = 0;
while (positionMillis < durationMillis
&& isPlayBinReady() ) {
ClockTime pos = null;
synchronized (playbinLock) {
pos = playbin2.queryPosition();
}
position = pos.toString();
positionMillis = pos.toMillis();
if (position.length() == 8) {
position = position.substring(3);
}
progressLabel.setText(position + "/" + finalDuration);
autoTracking = true;
progressSlider.setValue((int) positionMillis);
autoTracking = false;
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
}
}
if (finalDuration.length() == 5) {
progressLabel.setText("00:00/" + finalDuration);
} else {
progressLabel.setText("00:00:00/" + finalDuration);
}
// If it reached the end
if (progressSlider.getValue() == progressSlider.getMaximum()) {
restartVideo();
}
}
public void restartVideo() {
synchronized (playbinLock) {
if (playbin2 != null) {
playbin2.stop();
playbin2.setState(State.READY); // ready to be played again
}
}
pauseButton.setText("►");
progressSlider.setValue(0);
}
}).start();
}
| private void play() {
if (jFile == null || !jFile.exists()) {
progressLabel.setText("Error buffering file");
return;
}
ClockTime dur = null;
synchronized (playbinLock) {
playbin2.play(); // must play, then pause and get state to get duration.
playbin2.pause();
playbin2.getState();
dur = playbin2.queryDuration();
}
duration = dur.toString();
durationMillis = dur.toMillis();
progressSlider.setMaximum((int) durationMillis);
progressSlider.setMinimum(0);
final String finalDuration;
if (duration.length() == 8 && duration.substring(0, 3).equals("00:")) {
finalDuration = duration.substring(3);
progressLabel.setText("00:00/" + duration);
} else {
finalDuration = duration;
progressLabel.setText("00:00:00/" + duration);
}
synchronized (playbinLock) {
playbin2.play();
}
pauseButton.setText("||");
new Thread(new Runnable() {
private boolean isPlayBinReady() {
synchronized (playbinLock) {
return playbin2 != null && !playbin2.getState().equals(State.NULL);
}
}
@Override
public void run() {
long positionMillis = 0;
while (positionMillis < durationMillis
&& isPlayBinReady() ) {
ClockTime pos = null;
synchronized (playbinLock) {
pos = playbin2.queryPosition();
}
position = pos.toString();
positionMillis = pos.toMillis();
if (position.length() == 8) {
position = position.substring(3);
}
progressLabel.setText(position + "/" + finalDuration);
autoTracking = true;
progressSlider.setValue((int) positionMillis);
autoTracking = false;
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
}
}
if (finalDuration.length() == 5) {
progressLabel.setText("00:00/" + finalDuration);
} else {
progressLabel.setText("00:00:00/" + finalDuration);
}
// If it reached the end
if (progressSlider.getValue() == progressSlider.getMaximum()) {
restartVideo();
}
}
public void restartVideo() {
synchronized (playbinLock) {
if (playbin2 != null) {
playbin2.stop();
playbin2.setState(State.READY); // ready to be played again
}
}
pauseButton.setText("►");
progressSlider.setValue(0);
}
}).start();
}
|
diff --git a/src/com/dmdirc/commandparser/commands/global/Ifplugin.java b/src/com/dmdirc/commandparser/commands/global/Ifplugin.java
index 3d38e5f3b..910c7dbf5 100644
--- a/src/com/dmdirc/commandparser/commands/global/Ifplugin.java
+++ b/src/com/dmdirc/commandparser/commands/global/Ifplugin.java
@@ -1,126 +1,126 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.commandparser.commands.global;
import com.dmdirc.Config;
import com.dmdirc.commandparser.CommandManager;
import com.dmdirc.commandparser.GlobalCommand;
import com.dmdirc.commandparser.GlobalCommandParser;
import com.dmdirc.commandparser.IntelligentCommand;
import com.dmdirc.plugins.Plugin;
import com.dmdirc.plugins.PluginManager;
import com.dmdirc.ui.input.AdditionalTabTargets;
import com.dmdirc.ui.interfaces.InputWindow;
import java.util.Arrays;
import java.util.List;
/**
* The if plugin command allows the user to execute commands based on whether
* or not a plugin is loaded.
*
* @author chris
*/
public final class Ifplugin extends GlobalCommand implements IntelligentCommand {
/**
* Creates a new instance of Ifplugin.
*/
public Ifplugin() {
super();
CommandManager.registerCommand(this);
}
/** {@inheritDoc} */
public void execute(final InputWindow origin, final boolean isSilent,
final String... args) {
if (args.length <= 1) {
sendLine(origin, isSilent, "commandUsage", Config.getCommandChar(),
"ifplugin", "<[!]plugin> <command>");
return;
}
- final boolean negative = args[0].charAt(0) == '?';
+ final boolean negative = args[0].charAt(0) == '!';
final String pname = args[0].substring(negative ? 1 : 0);
final Plugin plugin = PluginManager.getPluginManager().getPlugin(pname);
boolean result = true;
if (plugin == null || !plugin.isActive()) {
result = false;
}
if (result != negative) {
if (origin == null) {
GlobalCommandParser.getGlobalCommandParser().parseCommand(null, implodeArgs(1, args));
} else {
origin.getCommandParser().parseCommand(origin, implodeArgs(1, args));
}
}
}
/** {@inheritDoc}. */
public String getName() {
return "ifplugin";
}
/** {@inheritDoc}. */
public boolean showInHelp() {
return true;
}
/** {@inheritDoc}. */
public boolean isPolyadic() {
return true;
}
/** {@inheritDoc}. */
public int getArity() {
return 0;
}
/** {@inheritDoc}. */
public String getHelp() {
return "ifplugin <[!]plugin> <command> - executes a command if the specified plugin is/isn't loaded";
}
/** {@inheritDoc} */
public AdditionalTabTargets getSuggestions(final int arg, final List<String> previousArgs) {
final AdditionalTabTargets res = new AdditionalTabTargets();
if (arg == 0) {
res.setIncludeNormal(false);
for (Plugin possPlugin : PluginManager.getPluginManager().getPossiblePlugins()) {
res.add(possPlugin.getClass().getCanonicalName());
res.add("!" + possPlugin.getClass().getCanonicalName());
}
}
return res;
}
}
| true | true | public void execute(final InputWindow origin, final boolean isSilent,
final String... args) {
if (args.length <= 1) {
sendLine(origin, isSilent, "commandUsage", Config.getCommandChar(),
"ifplugin", "<[!]plugin> <command>");
return;
}
final boolean negative = args[0].charAt(0) == '?';
final String pname = args[0].substring(negative ? 1 : 0);
final Plugin plugin = PluginManager.getPluginManager().getPlugin(pname);
boolean result = true;
if (plugin == null || !plugin.isActive()) {
result = false;
}
if (result != negative) {
if (origin == null) {
GlobalCommandParser.getGlobalCommandParser().parseCommand(null, implodeArgs(1, args));
} else {
origin.getCommandParser().parseCommand(origin, implodeArgs(1, args));
}
}
}
| public void execute(final InputWindow origin, final boolean isSilent,
final String... args) {
if (args.length <= 1) {
sendLine(origin, isSilent, "commandUsage", Config.getCommandChar(),
"ifplugin", "<[!]plugin> <command>");
return;
}
final boolean negative = args[0].charAt(0) == '!';
final String pname = args[0].substring(negative ? 1 : 0);
final Plugin plugin = PluginManager.getPluginManager().getPlugin(pname);
boolean result = true;
if (plugin == null || !plugin.isActive()) {
result = false;
}
if (result != negative) {
if (origin == null) {
GlobalCommandParser.getGlobalCommandParser().parseCommand(null, implodeArgs(1, args));
} else {
origin.getCommandParser().parseCommand(origin, implodeArgs(1, args));
}
}
}
|
diff --git a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/AdviceFileAdvice.java b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/AdviceFileAdvice.java
index 00785a27a..0980e6020 100644
--- a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/AdviceFileAdvice.java
+++ b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/eclipse/AdviceFileAdvice.java
@@ -1,200 +1,202 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation and others. All rights reserved. This
* program and the accompanying materials are made available under the terms of
* the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.equinox.p2.publisher.eclipse;
import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.p2.publisher.Activator;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactDescriptor;
import org.eclipse.equinox.internal.provisional.p2.core.Version;
import org.eclipse.equinox.internal.provisional.p2.metadata.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.MetadataFactory.InstallableUnitDescription;
import org.eclipse.equinox.p2.publisher.AbstractAdvice;
import org.eclipse.equinox.p2.publisher.actions.*;
/**
* Publishing advice from a p2 advice file. An advice file (p2.inf) can be embedded
* in the source of a bundle, feature, or product to specify additional advice to be
* added to the {@link IInstallableUnit} corresponding to the bundle, feature, or product.
*/
public class AdviceFileAdvice extends AbstractAdvice implements ITouchpointAdvice, ICapabilityAdvice, IPropertyAdvice, IAdditionalInstallableUnitAdvice {
/**
* The location of the bundle advice file, relative to the bundle root location.
*/
public static final IPath BUNDLE_ADVICE_FILE = new Path("META-INF/p2.inf"); //$NON-NLS-1$
private final String id;
private final Version version;
private Map touchpointInstructions;
private IProvidedCapability[] providedCapabilities;
private IRequiredCapability[] requiredCapabilities;
private Properties iuProperties;
private InstallableUnitDescription[] additionalIUs;
private boolean containsAdvice = false;
/**
* Creates advice for an advice file at the given location. If <tt>basePath</tt>
* is a directory, then <tt>adviceFilePath</tt> is appended to this location to
* obtain the location of the advice file. If <tt>basePath</tt> is a file, then
* <tt>adviceFilePath</tt> is used to
* @param id The symbolic id of the installable unit this advice applies to
* @param version The version of the installable unit this advice applies to
* @param basePath The root location of the the advice file. This is either the location of
* the jar containing the advice, or a directory containing the advice file
* @param adviceFilePath The location of the advice file within the base path. This is
* either the path of a jar entry, or the path of the advice file within the directory
* specified by the base path.
*/
public AdviceFileAdvice(String id, Version version, IPath basePath, IPath adviceFilePath) {
Assert.isNotNull(id);
Assert.isNotNull(version);
Assert.isNotNull(basePath);
Assert.isNotNull(adviceFilePath);
this.id = id;
this.version = version;
Map advice = loadAdviceMap(basePath, adviceFilePath);
if (advice.isEmpty())
return;
AdviceFileParser parser = new AdviceFileParser(id, version, advice);
try {
parser.parse();
} catch (Exception e) {
String message = "An error occured while parsing advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e);
LogHelper.log(status);
}
touchpointInstructions = parser.getTouchpointInstructions();
providedCapabilities = parser.getProvidedCapabilities();
requiredCapabilities = parser.getRequiredCapabilities();
iuProperties = parser.getProperties();
additionalIUs = parser.getAdditionalInstallableUnitDescriptions();
containsAdvice = true;
}
public boolean containsAdvice() {
return containsAdvice;
}
/**
* Loads the advice file and returns it in map form.
*/
private static Map loadAdviceMap(IPath basePath, IPath adviceFilePath) {
File location = basePath.toFile();
if (location == null || !location.exists())
return Collections.EMPTY_MAP;
ZipFile jar = null;
InputStream stream = null;
try {
if (location.isDirectory()) {
File adviceFile = new File(location, adviceFilePath.toString());
+ if (!adviceFile.isFile())
+ return Collections.EMPTY_MAP;
stream = new BufferedInputStream(new FileInputStream(adviceFile));
} else if (location.isFile()) {
jar = new ZipFile(location);
ZipEntry entry = jar.getEntry(adviceFilePath.toString());
if (entry == null)
return Collections.EMPTY_MAP;
stream = new BufferedInputStream(jar.getInputStream(entry));
}
Properties advice = new Properties();
advice.load(stream);
return (advice != null ? advice : Collections.EMPTY_MAP);
} catch (IOException e) {
String message = "An error occured while reading advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e);
LogHelper.log(status);
return Collections.EMPTY_MAP;
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
// ignore secondary failure
}
if (jar != null)
try {
jar.close();
} catch (IOException e) {
// ignore secondary failure
}
}
}
public boolean isApplicable(String configSpec, boolean includeDefault, String candidateId, Version candidateVersion) {
return id.equals(candidateId) && version.equals(candidateVersion);
}
/*(non-Javadoc)
* @see org.eclipse.equinox.p2.publisher.eclipse.ITouchpointAdvice#getTouchpointData()
*/
public ITouchpointData getTouchpointData(ITouchpointData existing) {
if (touchpointInstructions == null)
return existing;
Map resultInstructions = new HashMap(existing.getInstructions());
for (Iterator iterator = touchpointInstructions.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
ITouchpointInstruction instruction = (ITouchpointInstruction) touchpointInstructions.get(key);
ITouchpointInstruction existingInstruction = (ITouchpointInstruction) resultInstructions.get(key);
if (existingInstruction != null) {
String body = existingInstruction.getBody();
if (body == null || body.length() == 0)
body = instruction.getBody();
else if (instruction.getBody() != null) {
if (!body.endsWith(";")) //$NON-NLS-1$
body += ';';
body += instruction.getBody();
}
String importAttribute = existingInstruction.getImportAttribute();
if (importAttribute == null || importAttribute.length() == 0)
importAttribute = instruction.getImportAttribute();
else if (instruction.getImportAttribute() != null) {
if (!importAttribute.endsWith(",")) //$NON-NLS-1$
importAttribute += ',';
importAttribute += instruction.getBody();
}
instruction = MetadataFactory.createTouchpointInstruction(body, importAttribute);
}
resultInstructions.put(key, instruction);
}
return MetadataFactory.createTouchpointData(resultInstructions);
}
public IProvidedCapability[] getProvidedCapabilities(InstallableUnitDescription iu) {
return providedCapabilities;
}
public IRequiredCapability[] getRequiredCapabilities(InstallableUnitDescription iu) {
return requiredCapabilities;
}
public InstallableUnitDescription[] getAdditionalInstallableUnitDescriptions(IInstallableUnit iu) {
return additionalIUs;
}
public Properties getArtifactProperties(IInstallableUnit iu, IArtifactDescriptor descriptor) {
return null;
}
public Properties getInstallableUnitProperties(InstallableUnitDescription iu) {
return iuProperties;
}
}
| true | true | private static Map loadAdviceMap(IPath basePath, IPath adviceFilePath) {
File location = basePath.toFile();
if (location == null || !location.exists())
return Collections.EMPTY_MAP;
ZipFile jar = null;
InputStream stream = null;
try {
if (location.isDirectory()) {
File adviceFile = new File(location, adviceFilePath.toString());
stream = new BufferedInputStream(new FileInputStream(adviceFile));
} else if (location.isFile()) {
jar = new ZipFile(location);
ZipEntry entry = jar.getEntry(adviceFilePath.toString());
if (entry == null)
return Collections.EMPTY_MAP;
stream = new BufferedInputStream(jar.getInputStream(entry));
}
Properties advice = new Properties();
advice.load(stream);
return (advice != null ? advice : Collections.EMPTY_MAP);
} catch (IOException e) {
String message = "An error occured while reading advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e);
LogHelper.log(status);
return Collections.EMPTY_MAP;
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
// ignore secondary failure
}
if (jar != null)
try {
jar.close();
} catch (IOException e) {
// ignore secondary failure
}
}
}
| private static Map loadAdviceMap(IPath basePath, IPath adviceFilePath) {
File location = basePath.toFile();
if (location == null || !location.exists())
return Collections.EMPTY_MAP;
ZipFile jar = null;
InputStream stream = null;
try {
if (location.isDirectory()) {
File adviceFile = new File(location, adviceFilePath.toString());
if (!adviceFile.isFile())
return Collections.EMPTY_MAP;
stream = new BufferedInputStream(new FileInputStream(adviceFile));
} else if (location.isFile()) {
jar = new ZipFile(location);
ZipEntry entry = jar.getEntry(adviceFilePath.toString());
if (entry == null)
return Collections.EMPTY_MAP;
stream = new BufferedInputStream(jar.getInputStream(entry));
}
Properties advice = new Properties();
advice.load(stream);
return (advice != null ? advice : Collections.EMPTY_MAP);
} catch (IOException e) {
String message = "An error occured while reading advice file: basePath=" + basePath + ", adviceFilePath=" + adviceFilePath + "."; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
IStatus status = new Status(IStatus.ERROR, Activator.ID, message, e);
LogHelper.log(status);
return Collections.EMPTY_MAP;
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
// ignore secondary failure
}
if (jar != null)
try {
jar.close();
} catch (IOException e) {
// ignore secondary failure
}
}
}
|
diff --git a/rms/org.eclipse.ptp.rm.proxy.core/src/org/eclipse/ptp/rm/proxy/core/event/NodeEventFactory.java b/rms/org.eclipse.ptp.rm.proxy.core/src/org/eclipse/ptp/rm/proxy/core/event/NodeEventFactory.java
index 9c24d866b..3bc5e2e28 100644
--- a/rms/org.eclipse.ptp.rm.proxy.core/src/org/eclipse/ptp/rm/proxy/core/event/NodeEventFactory.java
+++ b/rms/org.eclipse.ptp.rm.proxy.core/src/org/eclipse/ptp/rm/proxy/core/event/NodeEventFactory.java
@@ -1,56 +1,56 @@
/*******************************************************************************
* Copyright (c) 2010 The University of Tennessee,
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Roland Schulz - initial implementation
*******************************************************************************/
package org.eclipse.ptp.rm.proxy.core.event;
import org.eclipse.ptp.proxy.event.IProxyEvent;
import org.eclipse.ptp.proxy.runtime.event.ProxyRuntimeEventFactory;
/**
* A factory for creating NodeEvent objects.
*/
public class NodeEventFactory implements IEventFactory {
private final ProxyRuntimeEventFactory fEventFactory = new ProxyRuntimeEventFactory();
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.rm.pbs.jproxy.core.IEventFactory#createChangeEvent(java
* .lang.String[])
*/
public IProxyEvent createChangeEvent(String[] args) {
- return fEventFactory.newProxyRuntimeJobChangeEvent(-1, args);
+ return fEventFactory.newProxyRuntimeNodeChangeEvent(-1, args);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.rm.pbs.jproxy.core.IEventFactory#createNewEvent(java.
* lang.String[])
*/
public IProxyEvent createNewEvent(String[] args) {
return fEventFactory.newProxyRuntimeNewNodeEvent(-1, args);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ptp.rm.pbs.jproxy.core.IEventFactory#createRemoveEvent(java
* .lang.String[])
*/
public IProxyEvent createRemoveEvent(String[] args) {
return fEventFactory.newProxyRuntimeRemoveNodeEvent(-1, args);
}
}
| true | true | public IProxyEvent createChangeEvent(String[] args) {
return fEventFactory.newProxyRuntimeJobChangeEvent(-1, args);
}
| public IProxyEvent createChangeEvent(String[] args) {
return fEventFactory.newProxyRuntimeNodeChangeEvent(-1, args);
}
|
diff --git a/Mediasystem/src/main/java/hs/mediasystem/dao/CastingsFetcher.java b/Mediasystem/src/main/java/hs/mediasystem/dao/CastingsFetcher.java
index cf80d4c7..2e853bcc 100644
--- a/Mediasystem/src/main/java/hs/mediasystem/dao/CastingsFetcher.java
+++ b/Mediasystem/src/main/java/hs/mediasystem/dao/CastingsFetcher.java
@@ -1,61 +1,61 @@
package hs.mediasystem.dao;
import hs.mediasystem.db.Fetcher;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Provider;
public class CastingsFetcher implements Fetcher<Item, Casting> {
private final Provider<Connection> connectionProvider;
public CastingsFetcher(Provider<Connection> connectionProvider) {
this.connectionProvider = connectionProvider;
}
@Override
public List<Casting> fetch(Item item) {
if(item.getId() == 0) {
return new ArrayList<>(0);
}
try(Connection connection = connectionProvider.get();
PreparedStatement statement = connection.prepareStatement("SELECT role, charactername, index, p.id, p.name, p.photourl, p.photo IS NOT NULL AS hasPhoto FROM castings c INNER JOIN persons p ON p.id = c.persons_id WHERE items_id = ? ORDER BY index")) {
statement.setInt(1, item.getId());
List<Casting> castings = new ArrayList<>();
try(ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
person.setPhotoURL(rs.getString("photourl"));
- person.setPhoto(new DatabaseImageSource(connectionProvider, person.getId(), "person", "photo", rs.getBoolean("hasPhoto") ? null : new URLImageSource(person.getPhotoURL())));
+ person.setPhoto(new DatabaseImageSource(connectionProvider, person.getId(), "persons", "photo", rs.getBoolean("hasPhoto") ? null : new URLImageSource(person.getPhotoURL())));
Casting casting = new Casting();
casting.setItem(item);
casting.setPerson(person);
casting.setCharacterName(rs.getString("charactername"));
casting.setIndex(rs.getInt("index"));
casting.setRole(rs.getString("role"));
castings.add(casting);
}
}
return castings;
}
catch(SQLException e) {
throw new RuntimeException(e);
}
}
}
| true | true | public List<Casting> fetch(Item item) {
if(item.getId() == 0) {
return new ArrayList<>(0);
}
try(Connection connection = connectionProvider.get();
PreparedStatement statement = connection.prepareStatement("SELECT role, charactername, index, p.id, p.name, p.photourl, p.photo IS NOT NULL AS hasPhoto FROM castings c INNER JOIN persons p ON p.id = c.persons_id WHERE items_id = ? ORDER BY index")) {
statement.setInt(1, item.getId());
List<Casting> castings = new ArrayList<>();
try(ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
person.setPhotoURL(rs.getString("photourl"));
person.setPhoto(new DatabaseImageSource(connectionProvider, person.getId(), "person", "photo", rs.getBoolean("hasPhoto") ? null : new URLImageSource(person.getPhotoURL())));
Casting casting = new Casting();
casting.setItem(item);
casting.setPerson(person);
casting.setCharacterName(rs.getString("charactername"));
casting.setIndex(rs.getInt("index"));
casting.setRole(rs.getString("role"));
castings.add(casting);
}
}
return castings;
}
catch(SQLException e) {
throw new RuntimeException(e);
}
}
| public List<Casting> fetch(Item item) {
if(item.getId() == 0) {
return new ArrayList<>(0);
}
try(Connection connection = connectionProvider.get();
PreparedStatement statement = connection.prepareStatement("SELECT role, charactername, index, p.id, p.name, p.photourl, p.photo IS NOT NULL AS hasPhoto FROM castings c INNER JOIN persons p ON p.id = c.persons_id WHERE items_id = ? ORDER BY index")) {
statement.setInt(1, item.getId());
List<Casting> castings = new ArrayList<>();
try(ResultSet rs = statement.executeQuery()) {
while(rs.next()) {
Person person = new Person();
person.setId(rs.getInt("id"));
person.setName(rs.getString("name"));
person.setPhotoURL(rs.getString("photourl"));
person.setPhoto(new DatabaseImageSource(connectionProvider, person.getId(), "persons", "photo", rs.getBoolean("hasPhoto") ? null : new URLImageSource(person.getPhotoURL())));
Casting casting = new Casting();
casting.setItem(item);
casting.setPerson(person);
casting.setCharacterName(rs.getString("charactername"));
casting.setIndex(rs.getInt("index"));
casting.setRole(rs.getString("role"));
castings.add(casting);
}
}
return castings;
}
catch(SQLException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/org.maven.ide.eclipse.editor/src/org/maven/ide/eclipse/editor/pom/MavenPomEditor.java b/org.maven.ide.eclipse.editor/src/org/maven/ide/eclipse/editor/pom/MavenPomEditor.java
index fc00db7d..de4df0b0 100644
--- a/org.maven.ide.eclipse.editor/src/org/maven/ide/eclipse/editor/pom/MavenPomEditor.java
+++ b/org.maven.ide.eclipse.editor/src/org/maven/ide/eclipse/editor/pom/MavenPomEditor.java
@@ -1,1034 +1,1034 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.maven.ide.eclipse.editor.pom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
import org.apache.maven.artifact.resolver.metadata.ArtifactMetadata;
import org.apache.maven.artifact.resolver.metadata.MetadataResolutionException;
import org.apache.maven.artifact.resolver.metadata.MetadataResolutionRequest;
import org.apache.maven.artifact.resolver.metadata.MetadataResolutionResult;
import org.apache.maven.artifact.resolver.metadata.MetadataResolver;
import org.apache.maven.embedder.MavenEmbedder;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.extension.ExtensionScanningException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.reactor.MavenExecutionException;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilderException;
import org.apache.maven.shared.dependency.tree.filter.ArtifactDependencyNodeFilter;
import org.apache.maven.shared.dependency.tree.traversal.BuildingDependencyNodeVisitor;
import org.apache.maven.shared.dependency.tree.traversal.FilteringDependencyNodeVisitor;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.util.IOUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.command.BasicCommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.search.ui.text.ISearchEditorAccess;
import org.eclipse.search.ui.text.Match;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IShowEditorInput;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IWindowListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.IFormPage;
import org.eclipse.ui.ide.IGotoMarker;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.progress.UIJob;
import org.eclipse.wst.common.internal.emf.resource.EMF2DOMRenderer;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.undo.IStructuredTextUndoManager;
import org.eclipse.wst.sse.ui.StructuredTextEditor;
import org.eclipse.wst.xml.core.internal.emf2xml.EMF2DOMSSEAdapter;
import org.eclipse.wst.xml.core.internal.emf2xml.EMF2DOMSSERenderer;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
import org.maven.ide.components.pom.Model;
import org.maven.ide.components.pom.util.PomResourceFactoryImpl;
import org.maven.ide.components.pom.util.PomResourceImpl;
import org.maven.ide.eclipse.MavenPlugin;
import org.maven.ide.eclipse.actions.SelectionUtil;
import org.maven.ide.eclipse.core.IMavenConstants;
import org.maven.ide.eclipse.core.MavenLogger;
import org.maven.ide.eclipse.editor.MavenEditorPlugin;
import org.maven.ide.eclipse.embedder.ArtifactKey;
import org.maven.ide.eclipse.embedder.MavenModelManager;
import org.maven.ide.eclipse.project.MavenProjectManager;
import org.maven.ide.eclipse.util.Util;
import org.maven.ide.eclipse.util.Util.FileStoreEditorInputStub;
/**
* Maven POM editor
*
* @author Eugene Kuleshov
* @author Anton Kraev
*/
@SuppressWarnings("restriction")
public class MavenPomEditor extends FormEditor implements IResourceChangeListener, IShowEditorInput, IGotoMarker,
ISearchEditorAccess, IEditingDomainProvider {
public static final String EDITOR_ID = "org.maven.ide.eclipse.editor.MavenPomEditor";
private static final String EXTENSION_FACTORIES = MavenEditorPlugin.PLUGIN_ID + ".pageFactories";
private static final String ELEMENT_PAGE = "factory";
OverviewPage overviewPage;
DependenciesPage dependenciesPage;
RepositoriesPage repositoriesPage;
BuildPage buildPage;
PluginsPage pluginsPage;
ReportingPage reportingPage;
ProfilesPage profilesPage;
TeamPage teamPage;
DependencyTreePage dependencyTreePage;
DependencyGraphPage graphPage;
StructuredTextEditor sourcePage;
List<MavenPomEditorPage> pages = new ArrayList<MavenPomEditorPage>();
private Model projectDocument;
private Map<String,DependencyNode> rootNode = new HashMap<String, DependencyNode>();
private PomResourceImpl resource;
IStructuredModel structuredModel;
EMF2DOMSSERenderer renderer;
private MavenProject mavenProject;
AdapterFactory adapterFactory;
AdapterFactoryEditingDomain editingDomain;
private int sourcePageIndex;
NotificationCommandStack commandStack;
IModelManager modelManager;
IFile pomFile;
MavenPomActivationListener activationListener;
boolean dirty;
CommandStackListener commandStackListener;
BasicCommandStack sseCommandStack;
List<IPomFileChangedListener> fileChangeListeners = new ArrayList<IPomFileChangedListener>();
public MavenPomEditor() {
modelManager = StructuredModelManager.getModelManager();
}
// IResourceChangeListener
/**
* Closes all project files on project close.
*/
public void resourceChanged(final IResourceChangeEvent event) {
if(pomFile == null) {
return;
}
//handle project delete
if(event.getType() == IResourceChangeEvent.PRE_CLOSE || event.getType() == IResourceChangeEvent.PRE_DELETE) {
if(pomFile.getProject().equals(event.getResource())) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
return;
}
//handle pom delete
class RemovedResourceDeltaVisitor implements IResourceDeltaVisitor {
boolean removed = false;
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource() == pomFile //
&& (delta.getKind() & (IResourceDelta.REMOVED)) != 0) {
removed = true;
return false;
}
return true;
}
};
try {
RemovedResourceDeltaVisitor visitor = new RemovedResourceDeltaVisitor();
event.getDelta().accept(visitor);
if(visitor.removed) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
} catch(CoreException ex) {
MavenLogger.log(ex);
}
// Reload model if pom file was changed externally.
// TODO implement generic merge scenario (when file is externally changed and is dirty)
class ChangedResourceDeltaVisitor implements IResourceDeltaVisitor {
public boolean visit(IResourceDelta delta) throws CoreException {
- if(delta.getResource().getName().equals(pomFile.getName()) //
+ if(delta.getResource().equals(pomFile)
&& (delta.getKind() & IResourceDelta.CHANGED) != 0 && delta.getResource().exists()) {
int flags = delta.getFlags();
if ((flags & (IResourceDelta.CONTENT | flags & IResourceDelta.REPLACED)) != 0) {
handleContentChanged();
return false;
}
if ((flags & IResourceDelta.MARKERS) != 0) {
handleMarkersChanged();
return false;
}
}
return true;
}
private void handleContentChanged() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
structuredModel.reload(pomFile.getContents());
reload();
} catch(CoreException e) {
MavenLogger.log(e);
} catch(Exception e) {
MavenLogger.log("Error loading pom editor model.", e);
}
}
});
}
private void handleMarkersChanged() {
try {
IMarker[] markers = pomFile.findMarkers(IMavenConstants.MARKER_ID, true, IResource.DEPTH_ZERO);
final String msg = markers != null && markers.length > 0 //
? markers[0].getAttribute(IMarker.MESSAGE, "Unknown error") : null;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
for(MavenPomEditorPage page : pages) {
page.setErrorMessage(msg, msg == null ? IMessageProvider.NONE : IMessageProvider.ERROR);
}
}
});
} catch (CoreException ex ) {
MavenLogger.log("Error updating pom file markers.", ex);
}
}
};
try {
ChangedResourceDeltaVisitor visitor = new ChangedResourceDeltaVisitor();
event.getDelta().accept(visitor);
} catch(CoreException ex) {
MavenLogger.log(ex);
}
}
public void reload() {
projectDocument = null;
try {
readProjectDocument();
} catch(CoreException e) {
MavenLogger.log(e);
}
for(MavenPomEditorPage page : pages) {
page.reload();
}
flushCommandStack();
}
void flushCommandStack() {
dirty = false;
if (sseCommandStack != null)
sseCommandStack.saveIsDone();
if (getContainer() != null && !getContainer().isDisposed())
getContainer().getDisplay().asyncExec(new Runnable() {
public void run() {
editorDirtyStateChanged();
}
});
}
protected void addPages() {
overviewPage = new OverviewPage(this);
addPomPage(overviewPage);
dependenciesPage = new DependenciesPage(this);
addPomPage(dependenciesPage);
repositoriesPage = new RepositoriesPage(this);
addPomPage(repositoriesPage);
buildPage = new BuildPage(this);
addPomPage(buildPage);
pluginsPage = new PluginsPage(this);
addPomPage(pluginsPage);
reportingPage = new ReportingPage(this);
addPomPage(reportingPage);
profilesPage = new ProfilesPage(this);
addPomPage(profilesPage);
teamPage = new TeamPage(this);
addPomPage(teamPage);
dependencyTreePage = new DependencyTreePage(this);
addPomPage(dependencyTreePage);
graphPage = new DependencyGraphPage(this);
addPomPage(graphPage);
addSourcePage();
addEditorPageExtensions();
}
protected void pageChange(int newPageIndex) {
super.pageChange(newPageIndex);
// a workaround for editor pages not returned
IEditorActionBarContributor contributor = getEditorSite().getActionBarContributor();
if(contributor != null && contributor instanceof MultiPageEditorActionBarContributor) {
IEditorPart activeEditor = getActivePageInstance();
((MultiPageEditorActionBarContributor) contributor).setActivePage(activeEditor);
}
}
private void addEditorPageExtensions() {
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint indexesExtensionPoint = registry.getExtensionPoint(EXTENSION_FACTORIES);
if(indexesExtensionPoint != null) {
IExtension[] indexesExtensions = indexesExtensionPoint.getExtensions();
for(IExtension extension : indexesExtensions) {
for(IConfigurationElement element : extension.getConfigurationElements()) {
if(element.getName().equals(ELEMENT_PAGE)) {
try {
MavenPomEditorPageFactory factory;
factory = (MavenPomEditorPageFactory) element.createExecutableExtension("class");
factory.addPages(this);
} catch(CoreException ex) {
MavenLogger.log(ex);
}
}
}
}
}
}
private void addSourcePage() {
sourcePage = new StructuredTextEditor() {
public void doSave(IProgressMonitor monitor) {
// always save text editor
ResourcesPlugin.getWorkspace().removeResourceChangeListener(MavenPomEditor.this);
try {
super.doSave(monitor);
flushCommandStack();
} finally {
ResourcesPlugin.getWorkspace().addResourceChangeListener(MavenPomEditor.this);
}
}
private boolean oldDirty;
public boolean isDirty() {
if (oldDirty != dirty) {
oldDirty = dirty;
updatePropertyDependentActions();
}
return dirty;
}
};
sourcePage.setEditorPart(this);
try {
sourcePageIndex = addPage(sourcePage, getEditorInput());
setPageText(sourcePageIndex, "pom.xml");
sourcePage.update();
IDocument doc = sourcePage.getDocumentProvider().getDocument(getEditorInput());
structuredModel = modelManager.getExistingModelForEdit(doc);
if(structuredModel == null) {
structuredModel = modelManager.getModelForEdit((IStructuredDocument) doc);
}
commandStackListener = new CommandStackListener() {
public void commandStackChanged(EventObject event) {
boolean oldDirty = dirty;
dirty = sseCommandStack.isSaveNeeded();
if (dirty != oldDirty)
MavenPomEditor.this.editorDirtyStateChanged();
}
};
IStructuredTextUndoManager undoManager = structuredModel.getUndoManager();
if(undoManager != null) {
sseCommandStack = (BasicCommandStack) undoManager.getCommandStack();
if(sseCommandStack != null) {
sseCommandStack.addCommandStackListener(commandStackListener);
}
}
flushCommandStack();
try {
readProjectDocument();
} catch(CoreException e) {
MavenLogger.log(e);
}
// TODO activate xml source page if model is empty or have errors
if(doc instanceof IStructuredDocument) {
List<AdapterFactoryImpl> factories = new ArrayList<AdapterFactoryImpl>();
factories.add(new ResourceItemProviderAdapterFactory());
factories.add(new ReflectiveItemProviderAdapterFactory());
adapterFactory = new ComposedAdapterFactory(factories);
commandStack = new NotificationCommandStack(this);
editingDomain = new AdapterFactoryEditingDomain(adapterFactory, //
commandStack, new HashMap<Resource, Boolean>());
if(resource != null && resource.getRenderer() instanceof EMF2DOMSSERenderer) {
renderer = (EMF2DOMSSERenderer) resource.getRenderer();
structuredModel.addModelStateListener(renderer);
structuredModel.addModelLifecycleListener(renderer);
}
}
} catch(PartInitException ex) {
MavenLogger.log(ex);
}
}
public boolean isReadOnly() {
return !(getEditorInput() instanceof IFileEditorInput);
}
private int addPomPage(IFormPage page) {
try {
if(page instanceof MavenPomEditorPage) {
pages.add((MavenPomEditorPage) page);
}
if (page instanceof IPomFileChangedListener) {
fileChangeListeners.add((IPomFileChangedListener) page);
}
return addPage(page);
} catch(PartInitException ex) {
MavenLogger.log(ex);
return -1;
}
}
public EditingDomain getEditingDomain() {
return editingDomain;
}
// XXX move to MavenModelManager (CommandStack and EditorDomain too)
public synchronized Model readProjectDocument() throws CoreException {
if(projectDocument == null) {
IEditorInput input = getEditorInput();
if(input instanceof IFileEditorInput) {
pomFile = ((IFileEditorInput) input).getFile();
pomFile.refreshLocal(1, null);
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
MavenModelManager modelManager = MavenPlugin.getDefault().getMavenModelManager();
PomResourceImpl resource = modelManager.loadResource(pomFile);
projectDocument = resource.getModel();
} else if(input instanceof IStorageEditorInput) {
IStorageEditorInput storageInput = (IStorageEditorInput) input;
IStorage storage = storageInput.getStorage();
IPath path = storage.getFullPath();
if(path == null || !new File(path.toOSString()).exists()) {
File tempPomFile = null;
InputStream is = null;
OutputStream os = null;
try {
tempPomFile = File.createTempFile("maven-pom", ".pom");
os = new FileOutputStream(tempPomFile);
is = storage.getContents();
IOUtil.copy(is, os);
projectDocument = loadModel(tempPomFile.getAbsolutePath());
} catch(IOException ex) {
MavenLogger.log("Can't close stream", ex);
} finally {
IOUtil.close(is);
IOUtil.close(os);
if(tempPomFile != null) {
tempPomFile.delete();
}
}
} else {
projectDocument = loadModel(path.toOSString());
}
} else if(input.getClass().getName().endsWith("FileStoreEditorInput")) {
projectDocument = loadModel(Util.proxy(input, FileStoreEditorInputStub.class).getURI().getPath());
}
}
return projectDocument;
}
private Model loadModel(String path) {
URI uri = URI.createFileURI(path);
PomResourceFactoryImpl factory = new PomResourceFactoryImpl();
resource = (PomResourceImpl) factory.createResource(uri);
// disable SSE support for read-only external documents
EMF2DOMRenderer renderer = new EMF2DOMRenderer();
renderer.setValidating(false);
resource.setRenderer(renderer);
try {
resource.load(Collections.EMPTY_MAP);
return resource.getModel();
} catch(Exception ex) {
MavenLogger.log("Can't load model " + path, ex);
return null;
}
}
/**
* @param force
* @param monitor
* @param scope one of
* {@link Artifact#SCOPE_COMPILE},
* {@link Artifact#SCOPE_TEST},
* {@link Artifact#SCOPE_SYSTEM},
* {@link Artifact#SCOPE_PROVIDED},
* {@link Artifact#SCOPE_RUNTIME}
*
* @return dependency node
*/
public synchronized DependencyNode readDependencies(boolean force, IProgressMonitor monitor, String scope) throws CoreException {
if(force || !rootNode.containsKey(scope)) {
MavenPlugin plugin = MavenPlugin.getDefault();
try {
monitor.setTaskName("Reading project");
MavenProject mavenProject = readMavenProject(force, monitor);
MavenProjectManager mavenProjectManager = plugin.getMavenProjectManager();
MavenEmbedder embedder = mavenProjectManager.createWorkspaceEmbedder();
try {
monitor.setTaskName("Building dependency tree");
PlexusContainer plexus = embedder.getPlexusContainer();
ArtifactFactory artifactFactory = (ArtifactFactory) plexus.lookup(ArtifactFactory.class);
ArtifactMetadataSource artifactMetadataSource = //
(ArtifactMetadataSource) plexus.lookup(ArtifactMetadataSource.class);
ArtifactCollector artifactCollector = (ArtifactCollector) plexus.lookup(ArtifactCollector.class);
ArtifactRepository localRepository = embedder.getLocalRepository();
DependencyTreeBuilder builder = (DependencyTreeBuilder) plexus.lookup(DependencyTreeBuilder.ROLE);
DependencyNode node = builder.buildDependencyTree(mavenProject, localRepository, artifactFactory,
artifactMetadataSource, null, artifactCollector);
BuildingDependencyNodeVisitor visitor = new BuildingDependencyNodeVisitor();
node.accept(new FilteringDependencyNodeVisitor(visitor,
new ArtifactDependencyNodeFilter(new ScopeArtifactFilter(scope))));
// node.accept(visitor);
rootNode.put(scope, visitor.getDependencyTree());
} finally {
embedder.stop();
}
} catch(MavenEmbedderException ex) {
String msg = "Can't create Maven embedder";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(ComponentLookupException ex) {
String msg = "Component lookup error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(DependencyTreeBuilderException ex) {
String msg = "Project read error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
}
}
return rootNode.get(scope);
}
public MavenProject readMavenProject(boolean force, IProgressMonitor monitor) throws MavenEmbedderException,
CoreException {
if(force || mavenProject == null) {
IEditorInput input = getEditorInput();
if(input instanceof IFileEditorInput) {
IFileEditorInput fileInput = (IFileEditorInput) input;
pomFile = fileInput.getFile();
pomFile.refreshLocal(1, null);
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
mavenProject = SelectionUtil.getMavenProject(input);
}
return mavenProject;
}
public MetadataResolutionResult readDependencyMetadata(IFile pomFile, IProgressMonitor monitor) throws CoreException {
File pom = pomFile.getLocation().toFile();
MavenPlugin plugin = MavenPlugin.getDefault();
MavenEmbedder embedder = null;
try {
MavenProjectManager mavenProjectManager = plugin.getMavenProjectManager();
embedder = mavenProjectManager.createWorkspaceEmbedder();
monitor.setTaskName("Reading project");
monitor.subTask("Reading project");
// ResolverConfiguration configuration = new ResolverConfiguration();
// MavenExecutionRequest request = embedderManager.createRequest(embedder);
// request.setPomFile(pom.getAbsolutePath());
// request.setBaseDirectory(pom.getParentFile());
// request.setTransferListener(new TransferListenerAdapter(monitor, console, indexManager));
// request.setProfiles(configuration.getActiveProfileList());
// request.addActiveProfiles(configuration.getActiveProfileList());
// request.setRecursive(false);
// request.setUseReactor(false);
// MavenExecutionResult result = projectManager.readProjectWithDependencies(embedder, pomFile, //
// configuration, offline, monitor);
// MavenExecutionResult result = embedder.readProjectWithDependencies(request);
// MavenProject project = result.getProject();
MavenProject project = embedder.readProject(pom);
if(project == null) {
return null;
}
ArtifactRepository localRepository = embedder.getLocalRepository();
@SuppressWarnings("unchecked")
List<ArtifactRepository> remoteRepositories = project.getRemoteArtifactRepositories();
PlexusContainer plexus = embedder.getPlexusContainer();
MetadataResolver resolver = (MetadataResolver) plexus.lookup(MetadataResolver.ROLE, "default");
ArtifactMetadata query = new ArtifactMetadata(project.getGroupId(), project.getArtifactId(), project.getVersion());
monitor.subTask("Building dependency graph...");
MetadataResolutionResult result = resolver.resolveMetadata( //
new MetadataResolutionRequest(query, localRepository, remoteRepositories));
if(result == null) {
return null;
}
monitor.subTask("Building dependency tree");
result.initTreeProcessing(plexus);
return result;
} catch(MetadataResolutionException ex) {
String msg = "Metadata resolution error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(ComponentLookupException ex) {
String msg = "Metadata resolver error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(ProjectBuildingException ex) {
String msg = "Metadata resolver error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(ExtensionScanningException ex) {
String msg = "Metadata resolver error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} catch(MavenExecutionException ex) {
String msg = "Metadata resolver error";
MavenLogger.log(msg, ex);
throw new CoreException(new Status(IStatus.ERROR, MavenEditorPlugin.PLUGIN_ID, -1, msg, ex));
} finally {
if(embedder != null) {
try {
embedder.stop();
} catch(MavenEmbedderException ex) {
MavenLogger.log("Can't stop Maven Embedder", ex);
}
}
}
}
public void dispose() {
new UIJob("Disposing") {
@SuppressWarnings("synthetic-access")
public IStatus runInUIThread(IProgressMonitor monitor) {
structuredModel.releaseFromEdit();
if (sseCommandStack != null)
sseCommandStack.removeCommandStackListener(commandStackListener);
if(activationListener != null) {
activationListener.dispose();
activationListener = null;
}
ResourcesPlugin.getWorkspace().removeResourceChangeListener(MavenPomEditor.this);
structuredModel.removeModelStateListener(renderer);
structuredModel.removeModelLifecycleListener(renderer);
MavenPomEditor.super.dispose();
return Status.OK_STATUS;
}
}.schedule();
}
/**
* Saves structured editor XXX form model need to be synchronized
*/
public void doSave(IProgressMonitor monitor) {
new UIJob("Saving") {
public IStatus runInUIThread(IProgressMonitor monitor) {
sourcePage.doSave(monitor);
return Status.OK_STATUS;
}
}.schedule();
}
public void doSaveAs() {
// IEditorPart editor = getEditor(0);
// editor.doSaveAs();
// setPageText(0, editor.getTitle());
// setInput(editor.getEditorInput());
}
/*
* (non-Javadoc) Method declared on IEditorPart.
*/
public boolean isSaveAsAllowed() {
return false;
}
public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
// if(!(editorInput instanceof IStorageEditorInput)) {
// throw new PartInitException("Unsupported editor input " + editorInput);
// }
setPartName(editorInput.getToolTipText());
// setContentDescription(name);
super.init(site, editorInput);
activationListener = new MavenPomActivationListener(site.getWorkbenchWindow().getPartService());
}
public void showInSourceEditor(EObject o) {
IDOMElement element = getElement(o);
if(element != null) {
int start = element.getStartOffset();
int lenght = element.getLength();
setActivePage(sourcePageIndex);
sourcePage.selectAndReveal(start, lenght);
}
}
public IDOMElement getElement(EObject o) {
for(Adapter adapter : o.eAdapters()) {
if(adapter instanceof EMF2DOMSSEAdapter) {
EMF2DOMSSEAdapter a = (EMF2DOMSSEAdapter) adapter;
if(a.getNode() instanceof IDOMElement) {
return (IDOMElement) a.getNode();
}
break;
}
}
return null;
}
// IShowEditorInput
public void showEditorInput(IEditorInput editorInput) {
// could activate different tabs based on the editor input
}
// IGotoMarker
public void gotoMarker(IMarker marker) {
// TODO use selection to activate corresponding form page elements
setActivePage(sourcePageIndex);
IGotoMarker adapter = (IGotoMarker) sourcePage.getAdapter(IGotoMarker.class);
adapter.gotoMarker(marker);
}
// ISearchEditorAccess
public IDocument getDocument(Match match) {
return sourcePage.getDocumentProvider().getDocument(getEditorInput());
}
public IAnnotationModel getAnnotationModel(Match match) {
return sourcePage.getDocumentProvider().getAnnotationModel(getEditorInput());
}
public boolean isDirty() {
return sourcePage.isDirty();
}
public List<MavenPomEditorPage> getPages() {
return pages;
}
public void showDependencyHierarchy(ArtifactKey artifactKey) {
setActivePage(dependencyTreePage.getId());
dependencyTreePage.selectDepedency(artifactKey);
}
/**
* Adapted from <code>org.eclipse.ui.texteditor.AbstractTextEditor.ActivationListener</code>
*/
class MavenPomActivationListener implements IPartListener, IWindowListener {
private IWorkbenchPart activePart;
private boolean isHandlingActivation = false;
private IPartService partService;
public MavenPomActivationListener(IPartService partService) {
this.partService = partService;
this.partService.addPartListener(this);
PlatformUI.getWorkbench().addWindowListener(this);
}
public void dispose() {
partService.removePartListener(this);
PlatformUI.getWorkbench().removeWindowListener(this);
partService = null;
}
// IPartListener
public void partActivated(IWorkbenchPart part) {
activePart = part;
handleActivation();
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
activePart = null;
}
public void partOpened(IWorkbenchPart part) {
}
// IWindowListener
public void windowActivated(IWorkbenchWindow window) {
if(window == getEditorSite().getWorkbenchWindow()) {
/*
* Workaround for problem described in
* http://dev.eclipse.org/bugs/show_bug.cgi?id=11731
* Will be removed when SWT has solved the problem.
*/
window.getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
handleActivation();
}
});
}
}
public void windowDeactivated(IWorkbenchWindow window) {
}
public void windowClosed(IWorkbenchWindow window) {
}
public void windowOpened(IWorkbenchWindow window) {
}
/**
* Handles the activation triggering a element state check in the editor.
*/
void handleActivation() {
if(isHandlingActivation) {
return;
}
if(activePart == MavenPomEditor.this) {
isHandlingActivation = true;
try {
final boolean[] changed = new boolean[] {false};
ITextListener listener = new ITextListener() {
public void textChanged(TextEvent event) {
changed[0] = true;
}
};
if (sourcePage != null) {
sourcePage.getTextViewer().addTextListener(listener);
try {
sourcePage.safelySanityCheckState(getEditorInput());
} finally {
sourcePage.getTextViewer().removeTextListener(listener);
}
}
if(changed[0]) {
try {
pomFile.refreshLocal(IResource.DEPTH_ZERO, null);
} catch(CoreException e) {
MavenLogger.log(e);
}
}
} finally {
isHandlingActivation = false;
}
}
}
}
public StructuredTextEditor getSourcePage() {
return sourcePage;
}
@Override
public IFormPage setActivePage(String pageId) {
if(pageId == null) {
setActivePage(sourcePageIndex);
}
return super.setActivePage(pageId);
}
@Override
@SuppressWarnings("unchecked")
public Object getAdapter(Class adapter) {
Object result = super.getAdapter(adapter);
if(result != null && Display.getCurrent() == null) {
return result;
}
return sourcePage.getAdapter(adapter);
}
public IFile getPomFile() {
return pomFile;
}
}
| true | true | public void resourceChanged(final IResourceChangeEvent event) {
if(pomFile == null) {
return;
}
//handle project delete
if(event.getType() == IResourceChangeEvent.PRE_CLOSE || event.getType() == IResourceChangeEvent.PRE_DELETE) {
if(pomFile.getProject().equals(event.getResource())) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
return;
}
//handle pom delete
class RemovedResourceDeltaVisitor implements IResourceDeltaVisitor {
boolean removed = false;
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource() == pomFile //
&& (delta.getKind() & (IResourceDelta.REMOVED)) != 0) {
removed = true;
return false;
}
return true;
}
};
try {
RemovedResourceDeltaVisitor visitor = new RemovedResourceDeltaVisitor();
event.getDelta().accept(visitor);
if(visitor.removed) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
} catch(CoreException ex) {
MavenLogger.log(ex);
}
// Reload model if pom file was changed externally.
// TODO implement generic merge scenario (when file is externally changed and is dirty)
class ChangedResourceDeltaVisitor implements IResourceDeltaVisitor {
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource().getName().equals(pomFile.getName()) //
&& (delta.getKind() & IResourceDelta.CHANGED) != 0 && delta.getResource().exists()) {
int flags = delta.getFlags();
if ((flags & (IResourceDelta.CONTENT | flags & IResourceDelta.REPLACED)) != 0) {
handleContentChanged();
return false;
}
if ((flags & IResourceDelta.MARKERS) != 0) {
handleMarkersChanged();
return false;
}
}
return true;
}
private void handleContentChanged() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
structuredModel.reload(pomFile.getContents());
reload();
} catch(CoreException e) {
MavenLogger.log(e);
} catch(Exception e) {
MavenLogger.log("Error loading pom editor model.", e);
}
}
});
}
private void handleMarkersChanged() {
try {
IMarker[] markers = pomFile.findMarkers(IMavenConstants.MARKER_ID, true, IResource.DEPTH_ZERO);
final String msg = markers != null && markers.length > 0 //
? markers[0].getAttribute(IMarker.MESSAGE, "Unknown error") : null;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
for(MavenPomEditorPage page : pages) {
page.setErrorMessage(msg, msg == null ? IMessageProvider.NONE : IMessageProvider.ERROR);
}
}
});
} catch (CoreException ex ) {
MavenLogger.log("Error updating pom file markers.", ex);
}
}
};
try {
ChangedResourceDeltaVisitor visitor = new ChangedResourceDeltaVisitor();
event.getDelta().accept(visitor);
} catch(CoreException ex) {
MavenLogger.log(ex);
}
}
| public void resourceChanged(final IResourceChangeEvent event) {
if(pomFile == null) {
return;
}
//handle project delete
if(event.getType() == IResourceChangeEvent.PRE_CLOSE || event.getType() == IResourceChangeEvent.PRE_DELETE) {
if(pomFile.getProject().equals(event.getResource())) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
return;
}
//handle pom delete
class RemovedResourceDeltaVisitor implements IResourceDeltaVisitor {
boolean removed = false;
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource() == pomFile //
&& (delta.getKind() & (IResourceDelta.REMOVED)) != 0) {
removed = true;
return false;
}
return true;
}
};
try {
RemovedResourceDeltaVisitor visitor = new RemovedResourceDeltaVisitor();
event.getDelta().accept(visitor);
if(visitor.removed) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
close(true);
}
});
}
} catch(CoreException ex) {
MavenLogger.log(ex);
}
// Reload model if pom file was changed externally.
// TODO implement generic merge scenario (when file is externally changed and is dirty)
class ChangedResourceDeltaVisitor implements IResourceDeltaVisitor {
public boolean visit(IResourceDelta delta) throws CoreException {
if(delta.getResource().equals(pomFile)
&& (delta.getKind() & IResourceDelta.CHANGED) != 0 && delta.getResource().exists()) {
int flags = delta.getFlags();
if ((flags & (IResourceDelta.CONTENT | flags & IResourceDelta.REPLACED)) != 0) {
handleContentChanged();
return false;
}
if ((flags & IResourceDelta.MARKERS) != 0) {
handleMarkersChanged();
return false;
}
}
return true;
}
private void handleContentChanged() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
try {
structuredModel.reload(pomFile.getContents());
reload();
} catch(CoreException e) {
MavenLogger.log(e);
} catch(Exception e) {
MavenLogger.log("Error loading pom editor model.", e);
}
}
});
}
private void handleMarkersChanged() {
try {
IMarker[] markers = pomFile.findMarkers(IMavenConstants.MARKER_ID, true, IResource.DEPTH_ZERO);
final String msg = markers != null && markers.length > 0 //
? markers[0].getAttribute(IMarker.MESSAGE, "Unknown error") : null;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
for(MavenPomEditorPage page : pages) {
page.setErrorMessage(msg, msg == null ? IMessageProvider.NONE : IMessageProvider.ERROR);
}
}
});
} catch (CoreException ex ) {
MavenLogger.log("Error updating pom file markers.", ex);
}
}
};
try {
ChangedResourceDeltaVisitor visitor = new ChangedResourceDeltaVisitor();
event.getDelta().accept(visitor);
} catch(CoreException ex) {
MavenLogger.log(ex);
}
}
|
diff --git a/src/com/example/digitalmeasuringtape/MainActivity.java b/src/com/example/digitalmeasuringtape/MainActivity.java
index ed52bce..bf9bc10 100644
--- a/src/com/example/digitalmeasuringtape/MainActivity.java
+++ b/src/com/example/digitalmeasuringtape/MainActivity.java
@@ -1,472 +1,472 @@
package com.example.digitalmeasuringtape;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable, SensorEventListener{
private static String pi_string;
private static TextView tv;
private boolean activeThread = true;
private boolean buttonDown = false;
private boolean calibrating = true;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private PhysicsManager physics;
public SharedPreferences sPrefs;
public TailLinkedList measurements;
public float greatestX, greatestY, greatestZ;
public CountDownLatch gate; //things call gate.await(), and get blocked.
//things become unblocked when gate.countDown()
//is called enough times, which will be 1
public ProgressWheel pw;
public MainActivity me = this;
protected void onExit()
{
if(mSensorManager != null)
mSensorManager.unregisterListener(this);
onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) this.findViewById(R.id.text1);
tv.setText("--");
sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
physics = new PhysicsManager(this);
//setting up sensor managers
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//hookup button
Button button = (Button)findViewById(R.id.button1);
button.setOnTouchListener(myListener);
//check if should popup
boolean helpme = sPrefs.getBoolean("help_me", false);
if (helpme)
{
//popup
}
//set up shared prefs
SharedPreferences.Editor editor = sPrefs.edit();
editor.putBoolean("MeasureX", true);
editor.putBoolean("MeasureY", false);
editor.putBoolean("MeasureZ", false);
editor.putBoolean("Eulers", false);
editor.putBoolean("ImprovedEulers", false);
editor.putBoolean("Simpsons", true);
editor.putBoolean("PathMode", false);
editor.commit();
//set up progress wheel settings
pw = (ProgressWheel) findViewById(R.id.pw_spinner);
pw.setSpinSpeed(50);
}
public void Calibrate()
{
//setting up sensor managers
SensorManager mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
greatestX = 0;
greatestY = 0;
greatestZ = 0;
System.out.println("Calibrate");
//make a fresh list, set gate as closed, register listener
measurements = new TailLinkedList();
boolean worked = mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
calibrating = true;
System.out.println("Return from registerlistener: " + worked );
try {
Thread.sleep(2000);
System.out.println("after sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
if (calibrating)
{
mSensorManager.unregisterListener(this, mAccelerometer);
}
calibrating = false;
measurements.unravel();
ArrayList<Float> xData = measurements.xData;
ArrayList<Float> yData = measurements.yData;
ArrayList<Float> zData = measurements.zData;
float xAvg = 0, yAvg = 0, zAvg = 0;
for(int i = 0; i < xData.size(); i ++)
{
xAvg += xData.get(i);
yAvg += yData.get(i);
zAvg += zData.get(i);
}
xAvg /= xData.size();
yAvg /= yData.size();
zAvg /= zData.size();
System.out.println("Gravity_x: " + xAvg);
System.out.println("Gravity_y: " + yAvg);
System.out.println("Gravity_z: " + zAvg);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putFloat("Gravity_x", xAvg);
editor.putFloat("Gravity_y", yAvg);
editor.putFloat("Gravity_z", zAvg);
editor.commit();
System.out.println("end calibrate");
}
@Override
protected void onRestart(){
super.onRestart();
//reset text view
// tv = (TextView) this.findViewById(R.id.text1);
// tv.setText("--");
}
//temporary to make sure this app isn't the one draining my battery...
@Override
protected void onStop(){
super.onStop();
onDestroy();
}
final CountDownTimer Count = new CountDownTimer(2000, 30){
public void onTick(long millisUntilFinished){
//counting down
pw.setProgress((int)(360 - (double)(millisUntilFinished)/2000 * 360));
if (!buttonDown)
{
if (calibrating)
{
mSensorManager.unregisterListener(me, mAccelerometer);
}
Count.cancel();
pw.resetCount();
tv.setText("--");
pw.stopSpinning();
}
}
public void onFinish(){
System.out.println("calibration finish");
pw.stopSpinning();
pw.resetCount();
//start recording
if (buttonDown)
{
start_distance_process();
}
}
};
private OnTouchListener myListener = new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
//calibrate for 2 seconds
buttonDown = true;
Count.start();
System.out.println("DOWN");
Thread thread = new Thread(me);
System.out.println("Started distance process.");
thread.start();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
System.out.println("UP");
buttonDown = false;
//kill thread on release of button
activeThread = false;
if(gate!=null)
gate.countDown();
}
return true;
}
};
//connected to button's onClick
public void start_distance_process(){
//start thread
// if (buttonDown)
// {
// Thread thread = new Thread(this);
// System.out.println("Started distance process.");
// thread.start();
// }
}
/************menu stuff**************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
// case R.id.about_menuitem:
// startActivity(new Intent(this, About.class));
case R.id.settings_menuitem:
startActivity(new Intent(this, Settings.class));
}
return true;
}
/***********end menu stuff***********/
//main method for thread
@Override
public void run()
{
if (buttonDown)
{
pi_string="Calibrating";
handler.sendEmptyMessage(0);
Calibrate();
}
if (buttonDown)
{
pi_string="GO!";
handler.sendEmptyMessage(0);
Measure();
}
}
@SuppressWarnings("unchecked")
public void Measure(){
System.out.println("Calling Measure");
Collect();
pi_string = "calculating";
handler.sendEmptyMessage(0);
measurements.trim(greatestX);
measurements.unravel();
//saving data
String xString = measurements.listToString(measurements.xData, "x");
String yString = measurements.listToString(measurements.yData, "y");
String tString = measurements.listToString(measurements.tData, "t");
measurements.writeGraph("graphs.csv", xString, yString, tString);
double d;
d = 0;
if (!sPrefs.getBoolean("MeasureY",false))
{
physics.RemoveGravity( measurements.xData );
physics.LowPassFilter( measurements.xData );
d = physics.Distance( measurements.xData,
measurements.tData);
}
else if(!sPrefs.getBoolean("MeasureZ", false))
{
physics.RemoveGravity( measurements.xData,
measurements.yData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.tData);
}
else
{
physics.RemoveGravity( measurements.xData,
measurements.yData,
measurements.zData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.zData,
measurements.tData);
}
//d.toString(), then truncate to two decimal places
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(3);
NumberFormat wnf = NumberFormat.getInstance();
wnf.setMinimumFractionDigits(0);
wnf.setMaximumFractionDigits(1);
String truncate;
// if(d == -1.0) truncate = "-1.0";
if(d == 0) truncate = "0.0";
else
{
truncate = nf.format(d);
}
if (d == Float.NaN)
{
- pi_string = "Error. Try Again.";
+ pi_string = "NaN. Try Again.";
}
- else if(d < 0) pi_string = "Error. Try Again.";
+ else if(d < 0) pi_string = "Eh, Try Again.";
else
{
//get shared setting for measurement units
SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String y = sPrefs.getString("meas_units", "0");
int UNITS = Integer.valueOf(y);
System.out.println("UNITS INT: " + UNITS);
if (UNITS == 0)
{
//convert to feet
System.out.println("truncate: " + truncate);
double x = Double.parseDouble(truncate) * 3.28084;
double f = (x - Math.floor(x)) * 12;
x = Math.floor(x);
String result = wnf.format(x);
String fraction = wnf.format(f);
System.out.println("double pi_string/truncate: " + result);
if (x==0)
{
pi_string = fraction + " in";
}
else{
pi_string = result + " ft " + fraction + " in";
}
}
else
{
pi_string = truncate + " m";
}
}
handler.sendEmptyMessage(0);
System.out.println(pi_string);
System.out.println("returning from Measure()");
}
//returns nothing, but results in "measurements" containing measured accels and angles
public void Collect(){
System.out.println("Calling Collect()");
SharedPreferences.Editor editor = sPrefs.edit();
measurements = new TailLinkedList();
greatestX = 0;
greatestY = 0;
greatestZ = 0;
gate = new CountDownLatch(1);
boolean worked = mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
System.out.println("Return from registerlistener: " + worked);
List<Sensor> l = mSensorManager.getSensorList(Sensor.TYPE_ALL);
for(Sensor s : l)
System.out.println(s.getName());
try {
gate.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
//stop measuring
mSensorManager.unregisterListener(this, mAccelerometer);
editor.putFloat("greatestX", greatestX);
editor.putFloat("greatestY", greatestY);
editor.putFloat("greatestZ", greatestZ);
editor.commit();
measurements.trim(greatestX);
System.out.println("returning from Collect()");
}
// manages user touching the screen
public boolean stopMeasuring(MotionEvent event) {
if (activeThread && event.getAction() == MotionEvent.ACTION_DOWN) {
// we set the activeThread boolean to false,
// forcing the loop from the Thread to end
activeThread = false;
gate.countDown(); //causes the thread's "run" method to contine.
//"opens the gate"
}
return super.onTouchEvent(event);
}
//Receive thread messages, interpret them and act as needed
@SuppressLint("HandlerLeak")
private static Handler handler = new Handler(){
@Override
public void handleMessage(Message mg){
tv.setText(pi_string);
}
};
@Override
public void onSensorChanged(SensorEvent event) {
float x=0;
float y=0;
float z=0;
long t=event.timestamp;
x = event.values[0];
if (sPrefs.getBoolean("MeasureY", false)) y = event.values[1];
if (sPrefs.getBoolean("MeasureZ", false)) z = event.values[2];
if(Math.abs(x) > Math.abs(greatestX)) greatestX = x;
if(Math.abs(y) > Math.abs(greatestY)) greatestY = y;
if(Math.abs(z) > Math.abs(greatestZ)) greatestZ = y;
if (!sPrefs.getBoolean("MeasureY", false)) measurements.add(t, x);
else if (!sPrefs.getBoolean("MeasureZ", false)) measurements.add(t, x, y);
else measurements.add(t, x, y, z);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
}
| false | true | public void Measure(){
System.out.println("Calling Measure");
Collect();
pi_string = "calculating";
handler.sendEmptyMessage(0);
measurements.trim(greatestX);
measurements.unravel();
//saving data
String xString = measurements.listToString(measurements.xData, "x");
String yString = measurements.listToString(measurements.yData, "y");
String tString = measurements.listToString(measurements.tData, "t");
measurements.writeGraph("graphs.csv", xString, yString, tString);
double d;
d = 0;
if (!sPrefs.getBoolean("MeasureY",false))
{
physics.RemoveGravity( measurements.xData );
physics.LowPassFilter( measurements.xData );
d = physics.Distance( measurements.xData,
measurements.tData);
}
else if(!sPrefs.getBoolean("MeasureZ", false))
{
physics.RemoveGravity( measurements.xData,
measurements.yData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.tData);
}
else
{
physics.RemoveGravity( measurements.xData,
measurements.yData,
measurements.zData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.zData,
measurements.tData);
}
//d.toString(), then truncate to two decimal places
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(3);
NumberFormat wnf = NumberFormat.getInstance();
wnf.setMinimumFractionDigits(0);
wnf.setMaximumFractionDigits(1);
String truncate;
// if(d == -1.0) truncate = "-1.0";
if(d == 0) truncate = "0.0";
else
{
truncate = nf.format(d);
}
if (d == Float.NaN)
{
pi_string = "Error. Try Again.";
}
else if(d < 0) pi_string = "Error. Try Again.";
else
{
//get shared setting for measurement units
SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String y = sPrefs.getString("meas_units", "0");
int UNITS = Integer.valueOf(y);
System.out.println("UNITS INT: " + UNITS);
if (UNITS == 0)
{
//convert to feet
System.out.println("truncate: " + truncate);
double x = Double.parseDouble(truncate) * 3.28084;
double f = (x - Math.floor(x)) * 12;
x = Math.floor(x);
String result = wnf.format(x);
String fraction = wnf.format(f);
System.out.println("double pi_string/truncate: " + result);
if (x==0)
{
pi_string = fraction + " in";
}
else{
pi_string = result + " ft " + fraction + " in";
}
}
else
{
pi_string = truncate + " m";
}
}
handler.sendEmptyMessage(0);
System.out.println(pi_string);
System.out.println("returning from Measure()");
}
| public void Measure(){
System.out.println("Calling Measure");
Collect();
pi_string = "calculating";
handler.sendEmptyMessage(0);
measurements.trim(greatestX);
measurements.unravel();
//saving data
String xString = measurements.listToString(measurements.xData, "x");
String yString = measurements.listToString(measurements.yData, "y");
String tString = measurements.listToString(measurements.tData, "t");
measurements.writeGraph("graphs.csv", xString, yString, tString);
double d;
d = 0;
if (!sPrefs.getBoolean("MeasureY",false))
{
physics.RemoveGravity( measurements.xData );
physics.LowPassFilter( measurements.xData );
d = physics.Distance( measurements.xData,
measurements.tData);
}
else if(!sPrefs.getBoolean("MeasureZ", false))
{
physics.RemoveGravity( measurements.xData,
measurements.yData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.tData);
}
else
{
physics.RemoveGravity( measurements.xData,
measurements.yData,
measurements.zData);
d = physics.Distance( measurements.xData,
measurements.yData,
measurements.zData,
measurements.tData);
}
//d.toString(), then truncate to two decimal places
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(3);
NumberFormat wnf = NumberFormat.getInstance();
wnf.setMinimumFractionDigits(0);
wnf.setMaximumFractionDigits(1);
String truncate;
// if(d == -1.0) truncate = "-1.0";
if(d == 0) truncate = "0.0";
else
{
truncate = nf.format(d);
}
if (d == Float.NaN)
{
pi_string = "NaN. Try Again.";
}
else if(d < 0) pi_string = "Eh, Try Again.";
else
{
//get shared setting for measurement units
SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String y = sPrefs.getString("meas_units", "0");
int UNITS = Integer.valueOf(y);
System.out.println("UNITS INT: " + UNITS);
if (UNITS == 0)
{
//convert to feet
System.out.println("truncate: " + truncate);
double x = Double.parseDouble(truncate) * 3.28084;
double f = (x - Math.floor(x)) * 12;
x = Math.floor(x);
String result = wnf.format(x);
String fraction = wnf.format(f);
System.out.println("double pi_string/truncate: " + result);
if (x==0)
{
pi_string = fraction + " in";
}
else{
pi_string = result + " ft " + fraction + " in";
}
}
else
{
pi_string = truncate + " m";
}
}
handler.sendEmptyMessage(0);
System.out.println(pi_string);
System.out.println("returning from Measure()");
}
|
diff --git a/src/ZoneDessin.java b/src/ZoneDessin.java
index 2f33b0c..bf95f9e 100755
--- a/src/ZoneDessin.java
+++ b/src/ZoneDessin.java
@@ -1,354 +1,354 @@
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
@SuppressWarnings("serial")
public class ZoneDessin extends JPanel{
int largeurDessin; //La largeur de la zone de dessin
int hauteurDessin; //La longueur de la zone de dessin
Color background;
Curseur curseur;
//Les bords de la zones de dessin
int ecartHorizontal;
int ecartVertical;
Controleur c;
BarreOutils barreOutils;
private int clicSouris;//1 : Clic gauche, 3 : Clic Droit
private Controleur controleur;
/**
* Constructeur de la zone de dessin
*/
ZoneDessin(int largeurDessin, int hauteurDessin, Color background, Curseur curseur){
this.largeurDessin = largeurDessin;
this.hauteurDessin = hauteurDessin;
this.background = background;
this.curseur = curseur;
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
clicSouris = e.getButton();
clicSouris(e.getX(), e.getY());
}
});
this.addMouseMotionListener(new MouseInputAdapter(){
public void mouseDragged(MouseEvent e) {
if(clicSouris == 1)
clicSouris(e.getX(), e.getY());
}
});
this.addMouseWheelListener(new MouseWheelListener(){
public void mouseWheelMoved(MouseWheelEvent e) {
barreOutils.interactionSliderEpaisseur(-e.getWheelRotation()*4);
}
});
}
public void clicSouris(int posX, int posY){
switch(clicSouris){
case 1 :
//if((posX > ecartHorizontal - 30) && (posX < ecartHorizontal + largeurDessin + 30) && (posY > ecartVertical - 30) && (posY < ecartVertical + hauteurDessin + 30)){
int posX_final = (posX - ecartHorizontal < 0) ? 0
: (posX - ecartHorizontal > this.getLargeurDessin()) ? this.getLargeurDessin()
: (posX - ecartHorizontal);
int posY_final = (posY - ecartVertical < 0) ? 0
: (posY - ecartVertical > this.getHauteurDessin()) ? this.getHauteurDessin()
: (posY - ecartVertical);
c.commande("goto " + posX_final + " " + posY_final, true );
repaint();
//}
break;
case 2 :
barreOutils.interactionBoutonOutil();
break;
case 3 :
barreOutils.interactionBoutonPoserOutil();
break;
}
}
/**
* Methode dessinant la zone de dessin puis le curseur
*/
public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//ETAPE 1 : Afficher la zone de dessin
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
int cap; int join;
if(t.getForme() == 0){
cap = BasicStroke.CAP_ROUND;
join = BasicStroke.JOIN_ROUND;
}
else{
cap = BasicStroke.CAP_BUTT;
join = BasicStroke.CAP_ROUND;
}
g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join));
/*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
*/
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
if(t.getForme() == 0)
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
//Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre
else{
g.setStroke(new BasicStroke());
g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
//Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné
int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2
};
int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2,
posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2
};
g.fillPolygon(x, y, 4);
int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2
};
g.fillPolygon(x2, y, 4);
}
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
- if(!t.estRempli()){
+ if(t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
//Si le t est une image
else if(t.getType() == 5){
try {
Image img = ImageIO.read(new File(t.getPath()));
g.drawImage(img, ecartHorizontal, ecartVertical, this);
//Pour une image de fond
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical);
g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
//DETERMINONS LA TAILLE DU JPANEL
this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin));
this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin));
this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin));
}
/*///
* ACCESSEURS
//*/
public int posXAbsolue(int x){
return x + ecartHorizontal;
}
public int posYAbsolue(int y){
return y + ecartVertical;
}
/*///
* ACCESSEURS
//*/
public int getPosX(){
return curseur.getPosX() + ecartHorizontal;
}
public int getPosY(){
return curseur.getPosY() + ecartVertical;
}
public int getEcartHorizontal(){
return ecartHorizontal;
}
public int getEcartVertical(){
return ecartVertical;
}
public int getLargeurDessin(){
return largeurDessin;
}
public int getHauteurDessin(){
return hauteurDessin;
}
public Color getBackground(){
return background;
}
/*///
* MODIFIEURS
//*/
/**
* Modifie le controleur
* @param c nouveau controleur
*/
public void setControleur(Controleur c)
{
this.c = c;
}
public void setBackground(Color c){
background = c;
}
public void setLargeur(int l){
largeurDessin = l;
}
public void setHauteur(int h){
hauteurDessin = h;
}
public void setBarreOutils(BarreOutils b){ barreOutils = b;}
}
| true | true | public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//ETAPE 1 : Afficher la zone de dessin
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
int cap; int join;
if(t.getForme() == 0){
cap = BasicStroke.CAP_ROUND;
join = BasicStroke.JOIN_ROUND;
}
else{
cap = BasicStroke.CAP_BUTT;
join = BasicStroke.CAP_ROUND;
}
g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join));
/*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
*/
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
if(t.getForme() == 0)
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
//Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre
else{
g.setStroke(new BasicStroke());
g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
//Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné
int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2
};
int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2,
posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2
};
g.fillPolygon(x, y, 4);
int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2
};
g.fillPolygon(x2, y, 4);
}
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
//Si le t est une image
else if(t.getType() == 5){
try {
Image img = ImageIO.read(new File(t.getPath()));
g.drawImage(img, ecartHorizontal, ecartVertical, this);
//Pour une image de fond
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical);
g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
//DETERMINONS LA TAILLE DU JPANEL
this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin));
this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin));
this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin));
}
| public void paintComponent(Graphics gd){
Graphics2D g = (Graphics2D)gd;
//Calcul de l'ecart de la zone de dessin pour centrer le dessin
ecartHorizontal = (this.getWidth() - largeurDessin)/2;
ecartVertical = (this.getHeight() - hauteurDessin)/2;
//ETAPE 1 : Afficher la zone de dessin
g.setColor(background);//Couleur de fond du dessin
g.fillRect(ecartHorizontal, ecartVertical, this.largeurDessin, this.hauteurDessin);
//ETAPE 2 : Afficher les traceurs
Traceur t;
for (int i = 0; i < StockageDonnee.liste_dessin.size(); i ++){
t = StockageDonnee.liste_dessin.get(i);
//Initialisons les propriétés de l'objet graphics
g.setColor(t.getColor());
int cap; int join;
if(t.getForme() == 0){
cap = BasicStroke.CAP_ROUND;
join = BasicStroke.JOIN_ROUND;
}
else{
cap = BasicStroke.CAP_BUTT;
join = BasicStroke.CAP_ROUND;
}
g.setStroke(new BasicStroke(t.getEpaisseur(), cap, join));
/*System.out.println("Position X Début : " + posXAbsolue(t.getXOrigine()));
System.out.println("Position Y Début : " + posYAbsolue(t.getYOrigine()));
System.out.println("Position X Fin : " + posXAbsolue(t.getXArrivee()));
System.out.println("Position Y Fin : " + posYAbsolue(t.getYArrivee()));
System.out.println("Couleur Curseur : " + t.getColor());
System.out.println("Epaisseur : " + t.getEpaisseur());
*/
//Si le t est une droite/point
if (t.getType() == 1 || t.getType() == 0){
if(t.getForme() == 0)
g.drawLine(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), posXAbsolue(t.getXArrivee()), posYAbsolue(t.getYArrivee()));
//Dans le cas d'une forme carré, on va dessiner des carré aux points de départ/arrivée pour un effet pls propre
else{
g.setStroke(new BasicStroke());
g.fillRect(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2, posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
g.fillRect(posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2, posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2, t.getEpaisseur(), t.getEpaisseur());
//Et on trace deux version du trait entre les points (en fait si on ne laisse qu'une seule des deux version, certains angles seront mal déssiné
int[] x = {posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2
};
int[] y = {posYAbsolue(t.getYOrigine()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) - t.getEpaisseur()/2,
posYAbsolue(t.getYArrivee()) + t.getEpaisseur()/2,
posYAbsolue(t.getYOrigine()) + t.getEpaisseur()/2
};
g.fillPolygon(x, y, 4);
int[] x2 = {posXAbsolue(t.getXOrigine()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) + t.getEpaisseur()/2,
posXAbsolue(t.getXArrivee()) - t.getEpaisseur()/2,
posXAbsolue(t.getXOrigine()) - t.getEpaisseur()/2
};
g.fillPolygon(x2, y, 4);
}
}
//Si le t est un Rectangle
else if (t.getType() == 2){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(t.estRempli()){
g.fillRect(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawRect(posXAbsolue(posXAbsolue(t.getXOrigine()) - t.getEpaisseur()), posYAbsolue(t.getYOrigine()) - t.getEpaisseur(), t.getLargeur() + t.getEpaisseur(), t.getHauteur() + t.getEpaisseur());
}
}
//Si le t est un triangle
else if (t.getType() == 3){
int[] x = {posXAbsolue(t.getXOrigine()),
posXAbsolue(t.getXArrivee()),
posXAbsolue(t.getX3())};
int[] y = {posYAbsolue(t.getYOrigine()),
posYAbsolue(t.getYArrivee()),
posYAbsolue(t.getY3())};
if(!t.estRempli()){
g.fillPolygon(x, y, 3);
}
else{
g.drawPolygon(x, y, 3);
}
}
//Si le t est un Cercle
else if (t.getType() == 4){
//On va faire une boucle qui dessin des triangle successifs selon l'epaisseur du curseur
if(!t.estRempli()){
g.fillOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
else{
g.drawOval(posXAbsolue(t.getXOrigine()), posYAbsolue(t.getYOrigine()), t.getLargeur(), t.getHauteur());
}
}
//Si le t est une image
else if(t.getType() == 5){
try {
Image img = ImageIO.read(new File(t.getPath()));
g.drawImage(img, ecartHorizontal, ecartVertical, this);
//Pour une image de fond
//g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//DESSINONS LE FOND
g.setStroke(new BasicStroke());
//Fond de la zone de dessin
g.setColor(new Color(180,180,180));//Couleur de fond
g.fillRect(0, 0, ecartHorizontal, this.getHeight());//On défini une couleur derriere le dessin pour eviter les glitch graphiques
g.fillRect(ecartHorizontal + largeurDessin, 0, this.getWidth(), this.getHeight());
g.fillRect(ecartHorizontal - 1, 0, largeurDessin + 1, ecartVertical);
g.fillRect(ecartHorizontal - 1, hauteurDessin + ecartVertical, largeurDessin + 1, ecartVertical+1);
//Ombre du dessin
g.setColor(new Color(220,220,220));
g.fillRect(ecartHorizontal + largeurDessin, ecartVertical + 5, 5, hauteurDessin);
g.fillRect(ecartHorizontal + 5, ecartVertical + hauteurDessin, largeurDessin, 5);
//ETAPE 3 : Afficher le curseur
//Deux curseurs à afficher : le curseur négatif (pour plus de lisibilité) et le curseur normal
//Forme du curseur en fonction de l'outil
BasicStroke forme;
if(curseur.getType() == 0){
forme = new BasicStroke(0);
}
else{
float[] dashArray = {2, 2};
forme = new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, dashArray, 0);
}
g.setStroke(forme);
//AFFICHAGE DE LA BASE DU CURSEUR
//Calcul du rayon de la base
int rayonBase;
if (curseur.getEpaisseur() > 10)
rayonBase = curseur.getEpaisseur() / 2;
else rayonBase = 5;
//Dessin de la base
//Sous curseur negatif
g.setColor(Color.white);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY() + 1, this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY() + 1);
g.drawLine(this.getPosX() + 1, this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX() +1, this.getPosY()+ (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase + 1, rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2 + 1, this.getPosY() - curseur.getEpaisseur()/2 + 1, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Curseur de la bonne couleur
g.setColor(Color.black);
g.drawLine(this.getPosX() - (curseur.getEpaisseur() / 2), this.getPosY(), this.getPosX() + (curseur.getEpaisseur() / 2), this.getPosY());
g.drawLine(this.getPosX(), this.getPosY() - (curseur.getEpaisseur() / 2), this.getPosX(), this.getPosY() + (curseur.getEpaisseur() / 2));
if (curseur.isDown()){
if(curseur.getForme() == 0)
g.drawOval(this.getPosX() - rayonBase, this.getPosY() - rayonBase , rayonBase * 2, rayonBase * 2);
else
g.drawRect(this.getPosX() - curseur.getEpaisseur()/2, this.getPosY() - curseur.getEpaisseur()/2, curseur.getEpaisseur(), curseur.getEpaisseur());
}
//Affichage de la fleche d'orientation
//Determinons le point d'arrivée du trait symbolisant l'orientation
int tailleTrait;
if (curseur.getEpaisseur() > 40)
tailleTrait = curseur.getEpaisseur();
else tailleTrait = 40;
double posX2 = this.getPosX() + tailleTrait * Math.sin(curseur.getOrientation() * Math.PI / 180);
double posY2 = this.getPosY() + tailleTrait * Math.cos(curseur.getOrientation() * Math.PI / 180);
//Dessinons le trait
g.setStroke(new BasicStroke(0));
g.drawLine(this.getPosX(), this.getPosY(), (int)posX2, (int)posY2);
g.setColor(Color.white);
g.drawLine(this.getPosX() - 1, this.getPosY() - 1, (int)posX2 - 1, (int)posY2 - 1);
//DETERMINONS LA TAILLE DU JPANEL
this.setPreferredSize(new Dimension(largeurDessin, hauteurDessin));
this.setMinimumSize(new Dimension(largeurDessin, hauteurDessin));
this.setMaximumSize(new Dimension(largeurDessin, hauteurDessin));
}
|
diff --git a/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java b/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java
index 9091b8ad0..dd63df877 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java
@@ -1,792 +1,793 @@
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.main;
import com.sun.tools.javac.code.Lint;
import com.sun.tools.javac.code.Source;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.jvm.Target;
import com.sun.tools.javac.main.JavacOption.HiddenOption;
import com.sun.tools.javac.main.JavacOption.Option;
import com.sun.tools.javac.main.JavacOption.COption;
import com.sun.tools.javac.main.JavacOption.XOption;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import javax.lang.model.SourceVersion;
import static com.sun.tools.javac.main.OptionName.*;
/**
* TODO: describe com.sun.tools.javac.main.RecognizedOptions
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own
* risk. This code and its internal interfaces are subject to change
* or deletion without notice.</b></p>
*/
public class RecognizedOptions {
private RecognizedOptions() {}
public interface OptionHelper {
void setOut(PrintWriter out);
void error(String key, Object... args);
void printVersion();
void printFullVersion();
void printHelp();
void printXhelp();
void addFile(File f);
void addClassName(String s);
}
public static class GrumpyHelper implements OptionHelper {
public void setOut(PrintWriter out) {
throw new IllegalArgumentException();
}
public void error(String key, Object... args) {
throw new IllegalArgumentException(Main.getLocalizedString(key, args));
}
public void printVersion() {
throw new IllegalArgumentException();
}
public void printFullVersion() {
throw new IllegalArgumentException();
}
public void printHelp() {
throw new IllegalArgumentException();
}
public void printXhelp() {
throw new IllegalArgumentException();
}
public void addFile(File f) {
throw new IllegalArgumentException(f.getPath());
}
public void addClassName(String s) {
throw new IllegalArgumentException(s);
}
}
static Set<OptionName> javacOptions = EnumSet.of(
G,
G_NONE,
G_CUSTOM,
XLINT,
XLINT_CUSTOM,
NOWARN,
VERBOSE,
VERBOSE_CUSTOM,
DEPRECATION,
CLASSPATH,
CP,
CEYLONREPO,
CEYLONSYSTEMREPO,
CEYLONUSER,
CEYLONPASS,
SOURCEPATH,
CEYLONSOURCEPATH,
BOOTCLASSPATH,
XBOOTCLASSPATH_PREPEND,
XBOOTCLASSPATH_APPEND,
XBOOTCLASSPATH,
EXTDIRS,
DJAVA_EXT_DIRS,
ENDORSEDDIRS,
DJAVA_ENDORSED_DIRS,
PROC,
PROCESSOR,
PROCESSORPATH,
D,
CEYLONOUT,
CEYLONOFFLINE,
S,
IMPLICIT,
ENCODING,
SOURCE,
TARGET,
VERSION,
FULLVERSION,
DIAGS,
HELP,
A,
X,
J,
MOREINFO,
WERROR,
// COMPLEXINFERENCE,
PROMPT,
DOE,
PRINTSOURCE,
WARNUNCHECKED,
XMAXERRS,
XMAXWARNS,
XSTDOUT,
XPKGINFO,
XPRINT,
XPRINTROUNDS,
XPRINTPROCESSORINFO,
XPREFER,
O,
XJCOV,
XD,
AT,
SOURCEFILE,
SRC,
BOOTSTRAPCEYLON,
CEYLONALLOWWARNINGS);
static Set<OptionName> javacFileManagerOptions = EnumSet.of(
CLASSPATH,
CP,
CEYLONREPO,
CEYLONSYSTEMREPO,
CEYLONUSER,
CEYLONPASS,
SOURCEPATH,
CEYLONSOURCEPATH,
BOOTCLASSPATH,
XBOOTCLASSPATH_PREPEND,
XBOOTCLASSPATH_APPEND,
XBOOTCLASSPATH,
EXTDIRS,
DJAVA_EXT_DIRS,
ENDORSEDDIRS,
DJAVA_ENDORSED_DIRS,
PROCESSORPATH,
D,
CEYLONOUT,
S,
ENCODING,
SOURCE,
SRC);
static Set<OptionName> javacToolOptions = EnumSet.of(
G,
G_NONE,
G_CUSTOM,
XLINT,
XLINT_CUSTOM,
NOWARN,
VERBOSE,
VERBOSE_CUSTOM,
DEPRECATION,
PROC,
PROCESSOR,
IMPLICIT,
SOURCE,
TARGET,
// VERSION,
// FULLVERSION,
// HELP,
A,
// X,
// J,
MOREINFO,
WERROR,
// COMPLEXINFERENCE,
PROMPT,
DOE,
PRINTSOURCE,
WARNUNCHECKED,
XMAXERRS,
XMAXWARNS,
// XSTDOUT,
XPKGINFO,
XPRINT,
XPRINTROUNDS,
XPRINTPROCESSORINFO,
XPREFER,
O,
XJCOV,
XD,
BOOTSTRAPCEYLON,
CEYLONALLOWWARNINGS);
public static Option[] getJavaCompilerOptions(OptionHelper helper) {
return getOptions(helper, javacOptions);
}
public static Option[] getJavacFileManagerOptions(OptionHelper helper) {
return getOptions(helper, javacFileManagerOptions);
}
public static Option[] getJavacToolOptions(OptionHelper helper) {
return getOptions(helper, javacToolOptions);
}
static Option[] getOptions(OptionHelper helper, Set<OptionName> desired) {
ListBuffer<Option> options = new ListBuffer<Option>();
for (Option option : getAll(helper))
if (desired.contains(option.getName()))
options.append(option);
return options.toArray(new Option[options.length()]);
}
/**
* Get all the recognized options.
* @param helper an {@code OptionHelper} to help when processing options
* @return an array of options
*/
public static Option[] getAll(final OptionHelper helper) {
return new Option[] {
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
@Override
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source",
Option.ChoiceKind.ANYOF, "lines", "vars", "source"),
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist",
Option.ChoiceKind.ANYOF, getXLintChoices()),
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-verbose:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(9);
options.put("-verbose:", suboptions);
// enter all the -verbose suboptions as "-verbose:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-verbose:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(CEYLONREPO, arg);
return false;
}
},
new COption(CEYLONSYSTEMREPO, "opt.arg.url", "opt.ceylonsystemrepo"),
new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"),
new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"),
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC, "opt.proc.none.only",
Option.ChoiceKind.ONEOF, "none", "only"),
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-d", arg);
}
},
new COption(CEYLONOFFLINE, "opt.ceylonoffline"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit",
Option.ChoiceKind.ONEOF, "none", "class"),
new Option(ENCODING, "opt.arg.encoding", "opt.encoding") {
@Override
public boolean process(Options options, String option, String operand) {
try {
Charset.forName(operand);
+ options.put(option, operand);
return false;
} catch (UnsupportedCharsetException e) {
helper.error("err.unsupported.encoding", operand);
return true;
} catch (IllegalCharsetNameException e) {
helper.error("err.unsupported.encoding", operand);
return true;
}
}
},
new Option(SOURCE, "opt.arg.release", "opt.source") {
@Override
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
@Override
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new COption(VERSION, "opt.version") {
@Override
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
@Override
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new HiddenOption(DIAGS) {
@Override
public boolean process(Options options, String option) {
Option xd = getOptions(helper, EnumSet.of(XD))[0];
option = option.substring(option.indexOf('=') + 1);
String diagsOption = option.contains("%") ?
"-XDdiagsFormat=" :
"-XDdiags=";
diagsOption += option;
if (xd.matches(diagsOption))
return xd.process(options, diagsOption);
else
return false;
}
},
new COption(HELP, "opt.help") {
@Override
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(A, "opt.arg.key.equals.value","opt.A") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean matches(String arg) {
return arg.startsWith("-A");
}
@Override
public boolean hasArg() {
return false;
}
// Mapping for processor options created in
// JavacProcessingEnvironment
@Override
public boolean process(Options options, String option) {
int argLength = option.length();
if (argLength == 2) {
helper.error("err.empty.A.argument");
return true;
}
int sepIndex = option.indexOf('=');
String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) );
if (!JavacProcessingEnvironment.isValidOptionName(key)) {
helper.error("err.invalid.A.key", option);
return true;
}
return process(options, option, option);
}
},
new Option(X, "opt.X") {
@Override
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
@Override
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new Option(WERROR, "opt.Werror"),
new Option(SRC, "opt.arg.src", "opt.src") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-src", arg);
}
},
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// allow us to compile ceylon.language
new HiddenOption(BOOTSTRAPCEYLON),
// do not halt on typechecker warnings
new HiddenOption(CEYLONALLOWWARNINGS),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
@Override
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer",
Option.ChoiceKind.ONEOF, "source", "newer"),
new XOption(XPKGINFO, "opt.pkginfo",
Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"),
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
@Override
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the CommandLine class.
new Option(AT, "opt.arg.file", "opt.AT") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the @ flag should be caught by CommandLine.");
}
},
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candidate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.endsWith(".java") // Java source file
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
|| "default".equals(s) // FIX for ceylon because default is not a valid name for Java
|| SourceVersion.isName(s); // Legal type name
}
@Override
public boolean process(Options options, String option) {
if (s.endsWith(".java")
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
) {
File f = new File(s);
if (!f.exists()) {
// -sourcepath not -src because the COption for
// CEYLONSOURCEPATH puts it in the options map as -sourcepath
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else {
// Should be a module name
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
String paths = sourcePaths.toString();
helper.error("err.module.not.found", s, paths.substring(1, paths.length()-1));
return true;
}
return false;
}
},
};
}
public enum PkgInfo {
ALWAYS, LEGACY, NONEMPTY;
public static PkgInfo get(Options options) {
String v = options.get(XPKGINFO);
return (v == null
? PkgInfo.LEGACY
: PkgInfo.valueOf(v.toUpperCase()));
}
}
private static Map<String,Boolean> getXLintChoices() {
Map<String,Boolean> choices = new LinkedHashMap<String,Boolean>();
choices.put("all", false);
for (Lint.LintCategory c : Lint.LintCategory.values())
choices.put(c.option, c.hidden);
for (Lint.LintCategory c : Lint.LintCategory.values())
choices.put("-" + c.option, c.hidden);
choices.put("none", false);
return choices;
}
}
| true | true | public static Option[] getAll(final OptionHelper helper) {
return new Option[] {
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
@Override
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source",
Option.ChoiceKind.ANYOF, "lines", "vars", "source"),
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist",
Option.ChoiceKind.ANYOF, getXLintChoices()),
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-verbose:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(9);
options.put("-verbose:", suboptions);
// enter all the -verbose suboptions as "-verbose:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-verbose:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(CEYLONREPO, arg);
return false;
}
},
new COption(CEYLONSYSTEMREPO, "opt.arg.url", "opt.ceylonsystemrepo"),
new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"),
new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"),
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC, "opt.proc.none.only",
Option.ChoiceKind.ONEOF, "none", "only"),
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-d", arg);
}
},
new COption(CEYLONOFFLINE, "opt.ceylonoffline"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit",
Option.ChoiceKind.ONEOF, "none", "class"),
new Option(ENCODING, "opt.arg.encoding", "opt.encoding") {
@Override
public boolean process(Options options, String option, String operand) {
try {
Charset.forName(operand);
return false;
} catch (UnsupportedCharsetException e) {
helper.error("err.unsupported.encoding", operand);
return true;
} catch (IllegalCharsetNameException e) {
helper.error("err.unsupported.encoding", operand);
return true;
}
}
},
new Option(SOURCE, "opt.arg.release", "opt.source") {
@Override
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
@Override
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new COption(VERSION, "opt.version") {
@Override
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
@Override
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new HiddenOption(DIAGS) {
@Override
public boolean process(Options options, String option) {
Option xd = getOptions(helper, EnumSet.of(XD))[0];
option = option.substring(option.indexOf('=') + 1);
String diagsOption = option.contains("%") ?
"-XDdiagsFormat=" :
"-XDdiags=";
diagsOption += option;
if (xd.matches(diagsOption))
return xd.process(options, diagsOption);
else
return false;
}
},
new COption(HELP, "opt.help") {
@Override
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(A, "opt.arg.key.equals.value","opt.A") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean matches(String arg) {
return arg.startsWith("-A");
}
@Override
public boolean hasArg() {
return false;
}
// Mapping for processor options created in
// JavacProcessingEnvironment
@Override
public boolean process(Options options, String option) {
int argLength = option.length();
if (argLength == 2) {
helper.error("err.empty.A.argument");
return true;
}
int sepIndex = option.indexOf('=');
String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) );
if (!JavacProcessingEnvironment.isValidOptionName(key)) {
helper.error("err.invalid.A.key", option);
return true;
}
return process(options, option, option);
}
},
new Option(X, "opt.X") {
@Override
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
@Override
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new Option(WERROR, "opt.Werror"),
new Option(SRC, "opt.arg.src", "opt.src") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-src", arg);
}
},
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// allow us to compile ceylon.language
new HiddenOption(BOOTSTRAPCEYLON),
// do not halt on typechecker warnings
new HiddenOption(CEYLONALLOWWARNINGS),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
@Override
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer",
Option.ChoiceKind.ONEOF, "source", "newer"),
new XOption(XPKGINFO, "opt.pkginfo",
Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"),
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
@Override
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the CommandLine class.
new Option(AT, "opt.arg.file", "opt.AT") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the @ flag should be caught by CommandLine.");
}
},
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candidate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.endsWith(".java") // Java source file
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
|| "default".equals(s) // FIX for ceylon because default is not a valid name for Java
|| SourceVersion.isName(s); // Legal type name
}
@Override
public boolean process(Options options, String option) {
if (s.endsWith(".java")
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
) {
File f = new File(s);
if (!f.exists()) {
// -sourcepath not -src because the COption for
// CEYLONSOURCEPATH puts it in the options map as -sourcepath
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else {
// Should be a module name
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
String paths = sourcePaths.toString();
helper.error("err.module.not.found", s, paths.substring(1, paths.length()-1));
return true;
}
return false;
}
},
};
}
| public static Option[] getAll(final OptionHelper helper) {
return new Option[] {
new Option(G, "opt.g"),
new Option(G_NONE, "opt.g.none") {
@Override
public boolean process(Options options, String option) {
options.put("-g:", "none");
return false;
}
},
new Option(G_CUSTOM, "opt.g.lines.vars.source",
Option.ChoiceKind.ANYOF, "lines", "vars", "source"),
new XOption(XLINT, "opt.Xlint"),
new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist",
Option.ChoiceKind.ANYOF, getXLintChoices()),
// -nowarn is retained for command-line backward compatibility
new Option(NOWARN, "opt.nowarn") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:none", option);
return false;
}
},
new Option(VERBOSE, "opt.verbose"),
new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") {
public boolean matches(String s) {
return s.startsWith("-verbose:");
}
public boolean process(Options options, String option) {
String suboptions = option.substring(9);
options.put("-verbose:", suboptions);
// enter all the -verbose suboptions as "-verbose:suboption"
for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) {
String tok = t.nextToken();
String opt = "-verbose:" + tok;
options.put(opt, opt);
}
return false;
}
},
// -deprecation is retained for command-line backward compatibility
new Option(DEPRECATION, "opt.deprecation") {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:deprecation", option);
return false;
}
},
new Option(CLASSPATH, "opt.arg.path", "opt.classpath"),
new Option(CP, "opt.arg.path", "opt.classpath") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-classpath", arg);
}
},
new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(CEYLONREPO, arg);
return false;
}
},
new COption(CEYLONSYSTEMREPO, "opt.arg.url", "opt.ceylonsystemrepo"),
new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"),
new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"),
new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){
@Override
public boolean process(Options options, String option, String arg) {
if(options != null)
options.addMulti(SOURCEPATH, arg);
return false;
}
},
new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, option, arg);
}
},
new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"),
new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"),
new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") {
@Override
public boolean process(Options options, String option, String arg) {
options.remove("-Xbootclasspath/p:");
options.remove("-Xbootclasspath/a:");
return super.process(options, "-bootclasspath", arg);
}
},
new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"),
new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-extdirs", arg);
}
},
new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"),
new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") {
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-endorseddirs", arg);
}
},
new Option(PROC, "opt.proc.none.only",
Option.ChoiceKind.ONEOF, "none", "only"),
new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"),
new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"),
new Option(D, "opt.arg.directory", "opt.d"),
new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){
@Override
public boolean process(Options options, String option, String arg) {
return super.process(options, "-d", arg);
}
},
new COption(CEYLONOFFLINE, "opt.ceylonoffline"),
new Option(S, "opt.arg.directory", "opt.sourceDest"),
new Option(IMPLICIT, "opt.implicit",
Option.ChoiceKind.ONEOF, "none", "class"),
new Option(ENCODING, "opt.arg.encoding", "opt.encoding") {
@Override
public boolean process(Options options, String option, String operand) {
try {
Charset.forName(operand);
options.put(option, operand);
return false;
} catch (UnsupportedCharsetException e) {
helper.error("err.unsupported.encoding", operand);
return true;
} catch (IllegalCharsetNameException e) {
helper.error("err.unsupported.encoding", operand);
return true;
}
}
},
new Option(SOURCE, "opt.arg.release", "opt.source") {
@Override
public boolean process(Options options, String option, String operand) {
Source source = Source.lookup(operand);
if (source == null) {
helper.error("err.invalid.source", operand);
return true;
}
return super.process(options, option, operand);
}
},
new Option(TARGET, "opt.arg.release", "opt.target") {
@Override
public boolean process(Options options, String option, String operand) {
Target target = Target.lookup(operand);
if (target == null) {
helper.error("err.invalid.target", operand);
return true;
}
return super.process(options, option, operand);
}
},
new COption(VERSION, "opt.version") {
@Override
public boolean process(Options options, String option) {
helper.printVersion();
return super.process(options, option);
}
},
new HiddenOption(FULLVERSION) {
@Override
public boolean process(Options options, String option) {
helper.printFullVersion();
return super.process(options, option);
}
},
new HiddenOption(DIAGS) {
@Override
public boolean process(Options options, String option) {
Option xd = getOptions(helper, EnumSet.of(XD))[0];
option = option.substring(option.indexOf('=') + 1);
String diagsOption = option.contains("%") ?
"-XDdiagsFormat=" :
"-XDdiags=";
diagsOption += option;
if (xd.matches(diagsOption))
return xd.process(options, diagsOption);
else
return false;
}
},
new COption(HELP, "opt.help") {
@Override
public boolean process(Options options, String option) {
helper.printHelp();
return super.process(options, option);
}
},
new Option(A, "opt.arg.key.equals.value","opt.A") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean matches(String arg) {
return arg.startsWith("-A");
}
@Override
public boolean hasArg() {
return false;
}
// Mapping for processor options created in
// JavacProcessingEnvironment
@Override
public boolean process(Options options, String option) {
int argLength = option.length();
if (argLength == 2) {
helper.error("err.empty.A.argument");
return true;
}
int sepIndex = option.indexOf('=');
String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) );
if (!JavacProcessingEnvironment.isValidOptionName(key)) {
helper.error("err.invalid.A.key", option);
return true;
}
return process(options, option, option);
}
},
new Option(X, "opt.X") {
@Override
public boolean process(Options options, String option) {
helper.printXhelp();
return super.process(options, option);
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the launcher.
new Option(J, "opt.arg.flag", "opt.J") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the -J flag should be caught by the launcher.");
}
},
// stop after parsing and attributing.
// new HiddenOption("-attrparseonly"),
// new Option("-moreinfo", "opt.moreinfo") {
new HiddenOption(MOREINFO) {
@Override
public boolean process(Options options, String option) {
Type.moreInfo = true;
return super.process(options, option);
}
},
// treat warnings as errors
new Option(WERROR, "opt.Werror"),
new Option(SRC, "opt.arg.src", "opt.src") {
public boolean process(Options options, String option, String arg) {
return super.process(options, "-src", arg);
}
},
// use complex inference from context in the position of a method call argument
new HiddenOption(COMPLEXINFERENCE),
// generare source stubs
// new HiddenOption("-stubs"),
// relax some constraints to allow compiling from stubs
// new HiddenOption("-relax"),
// output source after translating away inner classes
// new Option("-printflat", "opt.printflat"),
// new HiddenOption("-printflat"),
// display scope search details
// new Option("-printsearch", "opt.printsearch"),
// new HiddenOption("-printsearch"),
// prompt after each error
// new Option("-prompt", "opt.prompt"),
new HiddenOption(PROMPT),
// dump stack on error
new HiddenOption(DOE),
// output source after type erasure
// new Option("-s", "opt.s"),
new HiddenOption(PRINTSOURCE),
// allow us to compile ceylon.language
new HiddenOption(BOOTSTRAPCEYLON),
// do not halt on typechecker warnings
new HiddenOption(CEYLONALLOWWARNINGS),
// output shrouded class files
// new Option("-scramble", "opt.scramble"),
// new Option("-scrambleall", "opt.scrambleall"),
// display warnings for generic unchecked operations
new HiddenOption(WARNUNCHECKED) {
@Override
public boolean process(Options options, String option) {
options.put("-Xlint:unchecked", option);
return false;
}
},
new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"),
new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"),
new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") {
@Override
public boolean process(Options options, String option, String arg) {
try {
helper.setOut(new PrintWriter(new FileWriter(arg), true));
} catch (java.io.IOException e) {
helper.error("err.error.writing.file", arg, e);
return true;
}
return super.process(options, option, arg);
}
},
new XOption(XPRINT, "opt.print"),
new XOption(XPRINTROUNDS, "opt.printRounds"),
new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"),
new XOption(XPREFER, "opt.prefer",
Option.ChoiceKind.ONEOF, "source", "newer"),
new XOption(XPKGINFO, "opt.pkginfo",
Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"),
/* -O is a no-op, accepted for backward compatibility. */
new HiddenOption(O),
/* -Xjcov produces tables to support the code coverage tool jcov. */
new HiddenOption(XJCOV),
/* This is a back door to the compiler's option table.
* -XDx=y sets the option x to the value y.
* -XDx sets the option x to the value x.
*/
new HiddenOption(XD) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.startsWith(name.optionName);
}
@Override
public boolean process(Options options, String option) {
s = s.substring(name.optionName.length());
int eq = s.indexOf('=');
String key = (eq < 0) ? s : s.substring(0, eq);
String value = (eq < 0) ? s : s.substring(eq+1);
options.put(key, value);
return false;
}
},
// This option exists only for the purpose of documenting itself.
// It's actually implemented by the CommandLine class.
new Option(AT, "opt.arg.file", "opt.AT") {
@Override
String helpSynopsis() {
hasSuffix = true;
return super.helpSynopsis();
}
@Override
public boolean process(Options options, String option) {
throw new AssertionError
("the @ flag should be caught by CommandLine.");
}
},
/*
* TODO: With apt, the matches method accepts anything if
* -XclassAsDecls is used; code elsewhere does the lookup to
* see if the class name is both legal and found.
*
* In apt, the process method adds the candidate class file
* name to a separate list.
*/
new HiddenOption(SOURCEFILE) {
String s;
@Override
public boolean matches(String s) {
this.s = s;
return s.endsWith(".java") // Java source file
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
|| "default".equals(s) // FIX for ceylon because default is not a valid name for Java
|| SourceVersion.isName(s); // Legal type name
}
@Override
public boolean process(Options options, String option) {
if (s.endsWith(".java")
|| s.endsWith(".ceylon") // FIXME: Should be a FileManager query
) {
File f = new File(s);
if (!f.exists()) {
// -sourcepath not -src because the COption for
// CEYLONSOURCEPATH puts it in the options map as -sourcepath
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
helper.error("err.file.not.found", f);
return true;
}
if (!f.isFile()) {
helper.error("err.file.not.file", f);
return true;
}
helper.addFile(f);
}
else {
// Should be a module name
List<String> sourcePaths = options.getMulti("-sourcepath");
if(sourcePaths.isEmpty())
sourcePaths = Arrays.asList("source");// default value
// walk every path arg
for(String sourcePath : sourcePaths){
// split the path
for(String part : sourcePath.split("\\"+File.pathSeparator)){
// try to see if it's a module folder
File moduleFolder = new File(part, s.replace(".", File.separator));
if (moduleFolder.isDirectory()) {
// A Ceylon module name that ends with .ceylon or .java
helper.addClassName(s);
return false;
}
}
}
String paths = sourcePaths.toString();
helper.error("err.module.not.found", s, paths.substring(1, paths.length()-1));
return true;
}
return false;
}
},
};
}
|
diff --git a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandlerUnnormalised.java b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandlerUnnormalised.java
index 99e34fa3..2d4dd21e 100644
--- a/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandlerUnnormalised.java
+++ b/contrib/wikipedia/src/de/zib/scalaris/examples/wikipedia/ScalarisDataHandlerUnnormalised.java
@@ -1,679 +1,679 @@
/**
* Copyright 2012 Zuse Institute Berlin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.zib.scalaris.examples.wikipedia;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import de.zib.scalaris.Connection;
import de.zib.scalaris.ConnectionException;
import de.zib.scalaris.NotFoundException;
import de.zib.scalaris.Transaction;
import de.zib.scalaris.examples.wikipedia.Options.STORE_CONTRIB_TYPE;
import de.zib.scalaris.examples.wikipedia.bliki.MyNamespace;
import de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel;
import de.zib.scalaris.examples.wikipedia.bliki.NormalisedTitle;
import de.zib.scalaris.examples.wikipedia.data.Contribution;
import de.zib.scalaris.examples.wikipedia.data.Page;
import de.zib.scalaris.examples.wikipedia.data.Revision;
import de.zib.scalaris.examples.wikipedia.data.ShortRevision;
import de.zib.scalaris.examples.wikipedia.data.SiteInfo;
import de.zib.scalaris.operations.ReadOp;
/**
* @author Nico Kruber, [email protected]
*
*/
public class ScalarisDataHandlerUnnormalised extends ScalarisDataHandler {
/**
* Gets the key to store {@link Revision} objects at.
*
* @param title the title of the page
* @param id the id of the revision
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public static String getRevKey(String title, int id, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getRevKey(NormalisedTitle.fromUnnormalised(title, nsObject), id);
}
/**
* Gets the key to store {@link Page} objects at.
*
* @param title the title of the page
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getPageKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPageKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Gets the key to store the list of revisions of a page at.
*
* @param title the title of the page
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getRevListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getRevListKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Gets the key to store the list of pages belonging to a category at.
*
* @param title the category title (including <tt>Category:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getCatPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getCatPageListKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Gets the key to store the number of pages belonging to a category at.
*
* @param title the category title (including <tt>Category:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getCatPageCountKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getCatPageCountKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Gets the key to store the list of pages using a template at.
*
* @param title the template title (including <tt>Template:</tt>)
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getTplPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getTplPageListKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Gets the key to store the list of pages linking to the given title.
*
* @param title the page's title
* @param nsObject the namespace for page title normalisation
*
* @return Scalaris key
*/
public final static String getBackLinksPageListKey(String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getBackLinksPageListKey(NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves a page's history from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page history on success
*/
public static PageHistoryResult getPageHistory(Connection connection,
String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPageHistory(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves the current, i.e. most up-to-date, version of a page from
* Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page and revision on success
*/
public static RevisionResult getRevision(Connection connection,
String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getRevision(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves the given version of a page from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param id
* the id of the version
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page and revision on success
*/
public static RevisionResult getRevision(Connection connection,
String title, int id, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getRevision(connection, NormalisedTitle.fromUnnormalised(title, nsObject), id);
}
/**
* Retrieves the current version of all given pages from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param titles
* the titles of the pages
* @param nsObject
* the namespace for page title normalisation
* @param statName
* name of the statistic to collect
*
* @return a result object with the pages and revisions on success
*/
public static ValueResult<List<RevisionResult>> getRevisions(Connection connection,
Collection<String> titles, final String statName, final MyNamespace nsObject) {
final ArrayList<NormalisedTitle> normalisedTitles = new ArrayList<NormalisedTitle>(titles.size());
MyWikiModel.normalisePageTitles(titles, nsObject, normalisedTitles);
return ScalarisDataHandlerNormalised.getRevisions(connection, normalisedTitles, statName);
}
/**
* Retrieves a list of pages in the given category from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the category
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<NormalisedTitle>> getPagesInCategory(Connection connection,
String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPagesInCategory(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves a list of pages using the given template from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the template
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<NormalisedTitle>> getPagesInTemplate(Connection connection,
String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPagesInTemplate(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves a list of pages linking to the given page from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the page
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the page list on success
*/
public static ValueResult<List<NormalisedTitle>> getPagesLinkingTo(Connection connection,
String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPagesLinkingTo(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Retrieves the number of pages in the given category from Scalaris.
*
* @param connection
* the connection to Scalaris
* @param title
* the title of the category
* @param nsObject
* the namespace for page title normalisation
*
* @return a result object with the number of pages on success
*/
public static ValueResult<BigInteger> getPagesInCategoryCount(
Connection connection, String title, final MyNamespace nsObject) {
return ScalarisDataHandlerNormalised.getPagesInCategoryCount(connection, NormalisedTitle.fromUnnormalised(title, nsObject));
}
/**
* Saves or edits a page with the given parameters
*
* @param connection
* the connection to use
* @param title0
* the (unnormalised) title of the page
* @param newRev
* the new revision to add
* @param prevRevId
* the version of the previously existing revision or <tt>-1</tt>
* if there was no previous revision
* @param restrictions
* new restrictions of the page or <tt>null</tt> if they should
* not be changed
* @param siteinfo
* information about the wikipedia (used for parsing categories
* and templates)
* @param username
* name of the user editing the page (for enforcing restrictions)
* @param nsObject
* the namespace for page title normalisation
*
* @return success status
*/
public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
final NormalisedTitle normTitle = NormalisedTitle.fromUnnormalised(title0, nsObject);
final String normTitleStr = normTitle.toString();
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText(), true);
- timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
+ timeAtStart += (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText(), true);
- timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
+ timeAtStart += (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(normTitle.namespace, oldLnks, oldCats);
final boolean isArticle = (normTitle.namespace == 0)
&& MyWikiModel.isArticle(normTitle.namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, normTitleStr);
tplDiff.addScalarisOps(executor, normTitleStr);
lnkDiff.addScalarisOps(executor, normTitleStr);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(normTitle.namespace);
final String pageCountKey = getPageCountKey(normTitle.namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, normTitleStr, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
if (oldPage != null) {
executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
}
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
/**
* Increases the number of overall page edits statistic.
*
* @param scalaris_tx
* the transaction object to use
* @param involvedKeys
* all keys that have been read or written during the operation
*/
private static void increasePageEditStat(
Transaction scalaris_tx, List<InvolvedKey> involvedKeys) {
// increase number of page edits (for statistics)
// as this is not that important, use a separate transaction and do not
// fail if updating the value fails
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
executor.addIncrement(ScalarisOpType.EDIT_STAT, getStatsPageEditsKey(), 1);
try {
executor.getExecutor().run();
} catch (Exception e) {
}
}
/**
* Adds a contribution to the list of contributions of the user.
*
* @param scalaris_tx
* the transaction object to use
* @param oldPage
* the old page object or <tt>null</tt> if there was no old page
* @param newPage
* the newly created page object
* @param involvedKeys
* all keys that have been read or written during the operation
*/
private static void addContribution(
Transaction scalaris_tx, Page oldPage, Page newPage, List<InvolvedKey> involvedKeys) {
// as this is not that important, use a separate transaction and do not
// fail if updating the value fails
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
String scalaris_key = getContributionListKey(newPage.getCurRev().getContributor().toString());
executor.addAppend(ScalarisOpType.CONTRIBUTION, scalaris_key,
Arrays.asList(new Contribution(oldPage, newPage)), null);
try {
executor.getExecutor().run();
} catch (Exception e) {
}
}
/**
* Handles differences of sets.
*
* @author Nico Kruber, [email protected]
*/
private static class Difference {
public Set<String> onlyOld;
public Set<String> onlyNew;
@SuppressWarnings("unchecked")
private Set<String>[] changes = new Set[2];
private GetPageListKey keyGen;
final private ScalarisOpType opType;
/**
* Creates a new object calculating differences of two sets.
*
* @param oldSet
* the old set
* @param newSet
* the new set
* @param keyGen
* object creating the Scalaris key for the page lists (based
* on a set entry)
* @param opType
* operation type indicating what is being updated
*/
public Difference(Set<String> oldSet, Set<String> newSet,
GetPageListKey keyGen, ScalarisOpType opType) {
this.onlyOld = new HashSet<String>(oldSet);
this.onlyNew = new HashSet<String>(newSet);
this.onlyOld.removeAll(newSet);
this.onlyNew.removeAll(oldSet);
this.changes[0] = this.onlyOld;
this.changes[1] = this.onlyNew;
this.keyGen = keyGen;
this.opType = opType;
}
static public interface GetPageListKey {
/**
* Gets the Scalaris key for a page list for the given article's
* name.
*
* @param name the name of an article
* @return the key for Scalaris
*/
public abstract String getPageListKey(String name);
}
static public interface GetPageListAndCountKey extends GetPageListKey {
/**
* Gets the Scalaris key for a page list counter for the given
* article's name.
*
* @param name the name of an article
* @return the key for Scalaris
*/
public abstract String getPageCountKey(String name);
}
/**
* Adds the appropriate list append operations to the given executor.
*
* @param executor executor performing the Scalaris operations
* @param title (normalised) page name to update
*/
public void addScalarisOps(MyScalarisOpExecWrapper executor,
String title) {
String scalaris_key;
GetPageListAndCountKey keyCountGen = null;
if (keyGen instanceof GetPageListAndCountKey) {
keyCountGen = (GetPageListAndCountKey) keyGen;
}
// remove from old page list
for (String name: onlyOld) {
scalaris_key = keyGen.getPageListKey(name);
// System.out.println(scalaris_key + " -= " + title);
String scalaris_countKey = keyCountGen == null ? null : keyCountGen.getPageCountKey(name);
executor.addRemove(opType, scalaris_key, title, scalaris_countKey);
}
// add to new page list
for (String name: onlyNew) {
scalaris_key = keyGen.getPageListKey(name);
// System.out.println(scalaris_key + " += " + title);
String scalaris_countKey = keyCountGen == null ? null : keyCountGen.getPageCountKey(name);
executor.addAppend(opType, scalaris_key, title, scalaris_countKey);
}
}
}
}
| false | true | public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
final NormalisedTitle normTitle = NormalisedTitle.fromUnnormalised(title0, nsObject);
final String normTitleStr = normTitle.toString();
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText(), true);
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText(), true);
timeAtStart -= (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(normTitle.namespace, oldLnks, oldCats);
final boolean isArticle = (normTitle.namespace == 0)
&& MyWikiModel.isArticle(normTitle.namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, normTitleStr);
tplDiff.addScalarisOps(executor, normTitleStr);
lnkDiff.addScalarisOps(executor, normTitleStr);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(normTitle.namespace);
final String pageCountKey = getPageCountKey(normTitle.namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, normTitleStr, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
if (oldPage != null) {
executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
}
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
| public static SavePageResult savePage(final Connection connection, final String title0,
final Revision newRev, final int prevRevId, final Map<String, String> restrictions,
final SiteInfo siteinfo, final String username, final MyNamespace nsObject) {
long timeAtStart = System.currentTimeMillis();
final String statName = "saving " + title0;
Page oldPage = null;
Page newPage = null;
List<ShortRevision> newShortRevs = null;
BigInteger pageEdits = null;
List<InvolvedKey> involvedKeys = new ArrayList<InvolvedKey>();
if (connection == null) {
return new SavePageResult(false, involvedKeys,
"no connection to Scalaris", true, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
final NormalisedTitle normTitle = NormalisedTitle.fromUnnormalised(title0, nsObject);
final String normTitleStr = normTitle.toString();
Transaction scalaris_tx = new Transaction(connection);
// check that the current version is still up-to-date:
// read old version first, then write
String pageInfoKey = getPageKey(title0, nsObject);
Transaction.RequestList requests = new Transaction.RequestList();
requests.addOp(new ReadOp(pageInfoKey));
Transaction.ResultList results;
try {
addInvolvedKeys(involvedKeys, requests.getRequests());
results = scalaris_tx.req_list(requests);
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception getting page info (" + pageInfoKey
+ ") from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
int oldRevId;
try {
oldPage = results.processReadAt(0).jsonValue(Page.class);
newPage = new Page(oldPage.getTitle(), oldPage.getId(),
oldPage.isRedirect(), new LinkedHashMap<String, String>(
oldPage.getRestrictions()), newRev);
oldRevId = oldPage.getCurRev().getId();
} catch (NotFoundException e) {
// this is ok and means that the page did not exist yet
newPage = new Page(title0, 1, false,
new LinkedHashMap<String, String>(), newRev);
oldRevId = 0;
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception reading \"" + pageInfoKey
+ "\" from Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
newRev.setId(oldRevId + 1);
if (!newPage.checkEditAllowed(username)) {
return new SavePageResult(false, involvedKeys,
"operation not allowed: edit is restricted", false,
oldPage, newPage, newShortRevs, pageEdits,
statName, System.currentTimeMillis() - timeAtStart);
}
/*
* if prevRevId is greater than 0, it must match the old revision,
* if it is -1, then there should not be an old page
*/
if ((prevRevId > 0 && prevRevId != oldRevId) || (prevRevId == -1 && oldPage != null)) {
return new SavePageResult(false, involvedKeys, "curRev(" + oldRevId
+ ") != oldRev(" + prevRevId + ")", false, oldPage,
newPage, newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
// write:
// get previous categories, templates and backlinks:
final MyWikiModel wikiModel = new MyWikiModel("", "", new MyNamespace(siteinfo));
wikiModel.setPageName(title0);
Set<String> oldCats;
Set<String> oldTpls;
Set<String> oldLnks;
if (oldPage != null && oldPage.getCurRev() != null) {
// get a list of previous categories and templates:
wikiModel.setUp();
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, oldPage.getCurRev().unpackedText(), true);
timeAtStart += (System.currentTimeMillis() - timeAtRenderStart);
// note: no need to normalise the pages, we will do so during the write/read key generation
oldCats = wikiModel.getCategories().keySet();
oldTpls = wikiModel.getTemplates();
if (Options.getInstance().WIKI_USE_BACKLINKS) {
oldLnks = wikiModel.getLinks();
} else {
// use empty link lists to turn back-links off
oldLnks = new HashSet<String>();
}
wikiModel.tearDown();
} else {
oldCats = new HashSet<String>();
oldTpls = new HashSet<String>();
oldLnks = new HashSet<String>();
}
// get new categories and templates
wikiModel.setUp();
do {
final long timeAtRenderStart = System.currentTimeMillis();
wikiModel.render(null, newRev.unpackedText(), true);
timeAtStart += (System.currentTimeMillis() - timeAtRenderStart);
} while (false);
if (wikiModel.getRedirectLink() != null) {
newPage.setRedirect(true);
}
if (restrictions != null) {
newPage.setRestrictions(restrictions);
}
// note: do not tear down the wiki model - the following statements
// still need it and it will be removed at the end of the method anyway
// note: no need to normalise the pages, we will do so during the write/read key generation
final Set<String> newCats = wikiModel.getCategories().keySet();
Difference catDiff = new Difference(oldCats, newCats,
new Difference.GetPageListAndCountKey() {
@Override
public String getPageListKey(String name) {
return getCatPageListKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
@Override
public String getPageCountKey(String name) {
return getCatPageCountKey(
wikiModel.getCategoryNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.CATEGORY_PAGE_LIST);
final Set<String> newTpls = wikiModel.getTemplates();
Difference tplDiff = new Difference(oldTpls, newTpls,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getTplPageListKey(
wikiModel.getTemplateNamespace() + ":" + name,
nsObject);
}
}, ScalarisOpType.TEMPLATE_PAGE_LIST);
// use empty link lists to turn back-links off
final Set<String> newLnks = Options.getInstance().WIKI_USE_BACKLINKS ? wikiModel.getLinks() : new HashSet<String>();
Difference lnkDiff = new Difference(oldLnks, newLnks,
new Difference.GetPageListKey() {
@Override
public String getPageListKey(String name) {
return getBackLinksPageListKey(name, nsObject);
}
}, ScalarisOpType.BACKLINK_PAGE_LIST);
// now save the changes:
do {
final MyScalarisTxOpExecutor executor0 = new MyScalarisTxOpExecutor(
scalaris_tx, involvedKeys);
executor0.setCommitLast(true);
MyScalarisOpExecWrapper executor = new MyScalarisOpExecWrapper(
executor0);
int articleCountChange = 0;
final boolean wasArticle = (oldPage != null)
&& MyWikiModel.isArticle(normTitle.namespace, oldLnks, oldCats);
final boolean isArticle = (normTitle.namespace == 0)
&& MyWikiModel.isArticle(normTitle.namespace, newLnks, newCats);
if (wasArticle == isArticle) {
articleCountChange = 0;
} else if (!wasArticle) {
articleCountChange = 1;
} else if (!isArticle) {
articleCountChange = -1;
}
// PAGE LISTS UPDATE, step 1: append to / remove from old lists
executor.addAppend(ScalarisOpType.SHORTREV_LIST, getRevListKey(title0, nsObject), new ShortRevision(newRev), null);
if (articleCountChange != 0) {
executor.addIncrement(ScalarisOpType.ARTICLE_COUNT, getArticleCountKey(), articleCountChange);
}
// write differences (categories, templates, backlinks)
catDiff.addScalarisOps(executor, normTitleStr);
tplDiff.addScalarisOps(executor, normTitleStr);
lnkDiff.addScalarisOps(executor, normTitleStr);
// new page? -> add to page/article lists
if (oldPage == null) {
final String pageListKey = getPageListKey(normTitle.namespace);
final String pageCountKey = getPageCountKey(normTitle.namespace);
executor.addAppend(ScalarisOpType.PAGE_LIST, pageListKey, normTitleStr, pageCountKey);
}
executor.addWrite(ScalarisOpType.PAGE, getPageKey(title0, nsObject), newPage);
if (oldPage != null) {
executor.addWrite(ScalarisOpType.REVISION, getRevKey(title0, oldPage.getCurRev().getId(), nsObject), oldPage.getCurRev());
}
// PAGE LISTS UPDATE, step 2: execute and evaluate operations
try {
executor.getExecutor().run();
} catch (Exception e) {
return new SavePageResult(false, involvedKeys,
"unknown exception writing page \"" + title0
+ "\" to Scalaris: " + e.getMessage(),
e instanceof ConnectionException, oldPage, newPage,
newShortRevs, pageEdits, statName,
System.currentTimeMillis() - timeAtStart);
}
} while (false);
if (Options.getInstance().WIKI_STORE_CONTRIBUTIONS == STORE_CONTRIB_TYPE.OUTSIDE_TX) {
addContribution(scalaris_tx, oldPage, newPage, involvedKeys);
}
increasePageEditStat(scalaris_tx, involvedKeys);
return new SavePageResult(involvedKeys, oldPage, newPage, newShortRevs,
pageEdits, statName, System.currentTimeMillis() - timeAtStart);
}
|
diff --git a/src/main/java/com/appwish/web/IdeaController.java b/src/main/java/com/appwish/web/IdeaController.java
index 88af6fa..d4457af 100644
--- a/src/main/java/com/appwish/web/IdeaController.java
+++ b/src/main/java/com/appwish/web/IdeaController.java
@@ -1,69 +1,70 @@
package com.appwish.web;
import com.appwish.domain.Comment;
import com.appwish.domain.Idea;
import com.appwish.domain.Like;
import com.appwish.domain.UserAccount;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RooWebJson(jsonObject = Idea.class)
@Controller
@RequestMapping("/ideas")
public class IdeaController {
@RequestMapping(value="createmockups", method=RequestMethod.GET)
public void createMockups(){
UserAccount user1 = new UserAccount();
user1.setName("user1");
user1.setEmail("[email protected]");
user1.setCurrentDate();
Comment comment = new Comment();
comment.setBody("long ass first comment");
comment.setUserAccount(user1);
comment.setCurrentDate();
Comment comment1 = new Comment();
comment1.setBody("SECOND comment");
comment1.setUserAccount(user1);
comment1.setCurrentDate();
Like like1 = new Like();
like1.setUserAccount(user1);
for(int i = 1; i < 10; i++){
Idea idea = new Idea();
idea.setTitle("Some awesome idea " + i);
idea.setBody("Some awesome description");
idea.setUserAccount(user1);
idea.addComment(comment);
+ idea.setCurrentDate();
if (i == 7){
idea.addComment(comment1);
}
idea.addLikes(like1);
this.ideaRepository.save(idea);
}
}
@RequestMapping(value="getuserideas", method=RequestMethod.GET)
public void getUserIdeas(@ModelAttribute UserAccount userAccount){
this.ideaRepository.findByUserAccount(userAccount);
}
@RequestMapping(value="getlikedideas", method=RequestMethod.GET)
public void getLikedIdeas(UserAccount userAccount){
Like like = new Like();
like.setUserAccount(userAccount);
this.ideaRepository.findByLikes(like);
}
}
| true | true | public void createMockups(){
UserAccount user1 = new UserAccount();
user1.setName("user1");
user1.setEmail("[email protected]");
user1.setCurrentDate();
Comment comment = new Comment();
comment.setBody("long ass first comment");
comment.setUserAccount(user1);
comment.setCurrentDate();
Comment comment1 = new Comment();
comment1.setBody("SECOND comment");
comment1.setUserAccount(user1);
comment1.setCurrentDate();
Like like1 = new Like();
like1.setUserAccount(user1);
for(int i = 1; i < 10; i++){
Idea idea = new Idea();
idea.setTitle("Some awesome idea " + i);
idea.setBody("Some awesome description");
idea.setUserAccount(user1);
idea.addComment(comment);
if (i == 7){
idea.addComment(comment1);
}
idea.addLikes(like1);
this.ideaRepository.save(idea);
}
}
| public void createMockups(){
UserAccount user1 = new UserAccount();
user1.setName("user1");
user1.setEmail("[email protected]");
user1.setCurrentDate();
Comment comment = new Comment();
comment.setBody("long ass first comment");
comment.setUserAccount(user1);
comment.setCurrentDate();
Comment comment1 = new Comment();
comment1.setBody("SECOND comment");
comment1.setUserAccount(user1);
comment1.setCurrentDate();
Like like1 = new Like();
like1.setUserAccount(user1);
for(int i = 1; i < 10; i++){
Idea idea = new Idea();
idea.setTitle("Some awesome idea " + i);
idea.setBody("Some awesome description");
idea.setUserAccount(user1);
idea.addComment(comment);
idea.setCurrentDate();
if (i == 7){
idea.addComment(comment1);
}
idea.addLikes(like1);
this.ideaRepository.save(idea);
}
}
|
diff --git a/src/main/java/service/Simple.java b/src/main/java/service/Simple.java
index f356570..b879fc9 100644
--- a/src/main/java/service/Simple.java
+++ b/src/main/java/service/Simple.java
@@ -1,59 +1,59 @@
package service;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.xml.bind.JAXBException;
import models.A;
import models.B;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
@Path("/simple")
public class Simple {
A a;
public Simple(){
a = new A();
List<B> elBs = new ArrayList<B>();
B b = new B();
b.setDoubl(0.3);
elBs.add(b);
a.setElements(elBs);
a.setText("Message to the people");
}
@GET @Produces("application/json")
public A emptyGet(){
return a;
}
@GET @Path("/all") @Produces("application/json")
public Collection<B> getBs(){
return a.getElements();
}
@GET @Path("/string")
public String getJsoned() throws Exception{
// NOTE: this generates slighty different JSON ..
A myInstance = a;
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
- Class[] types = {A.class, B.class};
+ Class<?>[] types = {A.class, B.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
String json = writer.toString();
System.out.println(json);
return json;
}
}
| true | true | public String getJsoned() throws Exception{
// NOTE: this generates slighty different JSON ..
A myInstance = a;
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
Class[] types = {A.class, B.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
String json = writer.toString();
System.out.println(json);
return json;
}
| public String getJsoned() throws Exception{
// NOTE: this generates slighty different JSON ..
A myInstance = a;
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
Class<?>[] types = {A.class, B.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
String json = writer.toString();
System.out.println(json);
return json;
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyServiceMessageReceiver.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyServiceMessageReceiver.java
index 8fafcdc11..3ca76a998 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyServiceMessageReceiver.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyServiceMessageReceiver.java
@@ -1,229 +1,229 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.synapse.core.axis2;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.*;
import org.apache.synapse.mediators.MediatorFaultHandler;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.statistics.impl.ProxyServiceStatisticsStack;
/**
* This is the MessageReceiver set to act on behalf of Proxy services.
*/
public class ProxyServiceMessageReceiver extends SynapseMessageReceiver {
private static final Log log = LogFactory.getLog(ProxyServiceMessageReceiver.class);
private static final Log trace = LogFactory.getLog(SynapseConstants.TRACE_LOGGER);
/** The name of the Proxy Service */
private String name = null;
/** The proxy service */
private ProxyService proxy = null;
public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {
boolean traceOn = proxy.getTraceState() == SynapseConstants.TRACING_ON;
boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
String remoteAddr = (String) mc.getProperty(
org.apache.axis2.context.MessageContext.REMOTE_ADDR);
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Proxy Service " + name + " received a new message" +
(remoteAddr != null ? " from : " + remoteAddr : "..."));
traceOrDebug(traceOn, ("Message To: " +
(mc.getTo() != null ? mc.getTo().getAddress() : "null")));
traceOrDebug(traceOn, ("SOAPAction: " +
(mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
traceOrDebug(traceOn, ("WSA-Action: " +
(mc.getWSAAction() != null ? mc.getWSAAction() : "null")));
if (traceOn && trace.isTraceEnabled()) {
String[] cids = mc.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
- for (int i = 0; i < cids.length; i++) {
- trace.trace("With attachment content ID : " + cids[i]);
+ for (String cid : cids) {
+ trace.trace("With attachment content ID : " + cid);
}
}
trace.trace("Envelope : " + mc.getEnvelope());
}
}
MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
// get service log for this message and attach to the message context also set proxy name
Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
((Axis2MessageContext) synCtx).setServiceLog(serviceLog);
synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
synCtx.setTracingState(proxy.getTraceState());
try {
// Setting property to collect the proxy service statistics
boolean statsOn = (SynapseConstants.STATISTICS_ON == proxy.getStatisticsState());
if (statsOn) {
ProxyServiceStatisticsStack proxyServiceStatisticsStack
= new ProxyServiceStatisticsStack();
boolean isFault = synCtx.getEnvelope().getBody().hasFault();
proxyServiceStatisticsStack.put(name, System.currentTimeMillis(),
!synCtx.isResponse(), statsOn, isFault);
synCtx.setProperty(SynapseConstants.PROXY_STATS,
proxyServiceStatisticsStack);
}
// setup fault sequence - i.e. what happens when something goes wrong with this message
if (proxy.getTargetFaultSequence() != null) {
Mediator faultSequence = synCtx.getSequence(proxy.getTargetFaultSequence());
if (faultSequence != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn,
"Setting the fault-sequence to : " + faultSequence);
}
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(proxy.getTargetFaultSequence())));
} else {
// when we can not find the reference to the fault sequence of the proxy
// service we should not throw an exception because still we have the global
// fault sequence and the message mediation can still continue
traceOrDebug(traceOn, "Unable to find fault-sequence : " +
proxy.getTargetFaultSequence() + "; using default fault sequence");
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(SynapseConstants.FAULT_SEQUENCE_KEY)));
}
} else if (proxy.getTargetInLineFaultSequence() != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Setting specified anonymous fault-sequence for proxy");
}
synCtx.pushFaultHandler(
new MediatorFaultHandler(proxy.getTargetInLineFaultSequence()));
}
boolean inSequenceResult = true;
// Using inSequence for the incoming message mediation
if (proxy.getTargetInSequence() != null) {
Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
if (inSequence != null) {
traceOrDebug(traceOn, "Using sequence named : "
+ proxy.getTargetInSequence() + " for incoming message mediation");
inSequenceResult = inSequence.mediate(synCtx);
} else {
handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
}
} else if (proxy.getTargetInLineInSequence() != null) {
traceOrDebug(traceOn, "Using the anonymous " +
"in-sequence of the proxy service for mediation");
inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
}
// if inSequence returns true, forward message to endpoint
- if(inSequenceResult == true) {
+ if(inSequenceResult) {
if (proxy.getTargetEndpoint() != null) {
Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());
if (endpoint != null) {
traceOrDebug(traceOn, "Forwarding message to the endpoint : "
+ proxy.getTargetEndpoint());
endpoint.send(synCtx);
} else {
handleException("Unable to find the endpoint specified : " +
proxy.getTargetEndpoint(), synCtx);
}
} else if (proxy.getTargetInLineEndpoint() != null) {
traceOrDebug(traceOn, "Forwarding the message to the anonymous " +
"endpoint of the proxy service");
proxy.getTargetInLineEndpoint().send(synCtx);
}
}
} catch (SynapseException syne) {
if (!synCtx.getFaultStack().isEmpty()) {
warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);
} else {
warn(traceOn, "Exception encountered but no fault handler found - " +
"message dropped", synCtx);
}
}
}
/**
* Set the name of the corresponding proxy service
*
* @param name the proxy service name
*/
public void setName(String name) {
this.name = name;
}
/**
* Set reference to actual proxy service
* @param proxy
*/
public void setProxy(ProxyService proxy) {
this.proxy = proxy;
}
private void traceOrDebug(boolean traceOn, String msg) {
if (traceOn) {
trace.info(msg);
}
if (log.isDebugEnabled()) {
log.debug(msg);
}
}
private void warn(boolean traceOn, String msg, MessageContext msgContext) {
if (traceOn) {
trace.warn(msg);
}
if (log.isDebugEnabled()) {
log.warn(msg);
}
if (msgContext.getServiceLog() != null) {
msgContext.getServiceLog().warn(msg);
}
}
private void handleException(String msg, MessageContext msgContext) {
log.error(msg);
if (msgContext.getServiceLog() != null) {
msgContext.getServiceLog().error(msg);
}
if (proxy.getTraceState() == SynapseConstants.TRACING_ON) {
trace.error(msg);
}
throw new SynapseException(msg);
}
}
| false | true | public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {
boolean traceOn = proxy.getTraceState() == SynapseConstants.TRACING_ON;
boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
String remoteAddr = (String) mc.getProperty(
org.apache.axis2.context.MessageContext.REMOTE_ADDR);
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Proxy Service " + name + " received a new message" +
(remoteAddr != null ? " from : " + remoteAddr : "..."));
traceOrDebug(traceOn, ("Message To: " +
(mc.getTo() != null ? mc.getTo().getAddress() : "null")));
traceOrDebug(traceOn, ("SOAPAction: " +
(mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
traceOrDebug(traceOn, ("WSA-Action: " +
(mc.getWSAAction() != null ? mc.getWSAAction() : "null")));
if (traceOn && trace.isTraceEnabled()) {
String[] cids = mc.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (int i = 0; i < cids.length; i++) {
trace.trace("With attachment content ID : " + cids[i]);
}
}
trace.trace("Envelope : " + mc.getEnvelope());
}
}
MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
// get service log for this message and attach to the message context also set proxy name
Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
((Axis2MessageContext) synCtx).setServiceLog(serviceLog);
synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
synCtx.setTracingState(proxy.getTraceState());
try {
// Setting property to collect the proxy service statistics
boolean statsOn = (SynapseConstants.STATISTICS_ON == proxy.getStatisticsState());
if (statsOn) {
ProxyServiceStatisticsStack proxyServiceStatisticsStack
= new ProxyServiceStatisticsStack();
boolean isFault = synCtx.getEnvelope().getBody().hasFault();
proxyServiceStatisticsStack.put(name, System.currentTimeMillis(),
!synCtx.isResponse(), statsOn, isFault);
synCtx.setProperty(SynapseConstants.PROXY_STATS,
proxyServiceStatisticsStack);
}
// setup fault sequence - i.e. what happens when something goes wrong with this message
if (proxy.getTargetFaultSequence() != null) {
Mediator faultSequence = synCtx.getSequence(proxy.getTargetFaultSequence());
if (faultSequence != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn,
"Setting the fault-sequence to : " + faultSequence);
}
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(proxy.getTargetFaultSequence())));
} else {
// when we can not find the reference to the fault sequence of the proxy
// service we should not throw an exception because still we have the global
// fault sequence and the message mediation can still continue
traceOrDebug(traceOn, "Unable to find fault-sequence : " +
proxy.getTargetFaultSequence() + "; using default fault sequence");
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(SynapseConstants.FAULT_SEQUENCE_KEY)));
}
} else if (proxy.getTargetInLineFaultSequence() != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Setting specified anonymous fault-sequence for proxy");
}
synCtx.pushFaultHandler(
new MediatorFaultHandler(proxy.getTargetInLineFaultSequence()));
}
boolean inSequenceResult = true;
// Using inSequence for the incoming message mediation
if (proxy.getTargetInSequence() != null) {
Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
if (inSequence != null) {
traceOrDebug(traceOn, "Using sequence named : "
+ proxy.getTargetInSequence() + " for incoming message mediation");
inSequenceResult = inSequence.mediate(synCtx);
} else {
handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
}
} else if (proxy.getTargetInLineInSequence() != null) {
traceOrDebug(traceOn, "Using the anonymous " +
"in-sequence of the proxy service for mediation");
inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
}
// if inSequence returns true, forward message to endpoint
if(inSequenceResult == true) {
if (proxy.getTargetEndpoint() != null) {
Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());
if (endpoint != null) {
traceOrDebug(traceOn, "Forwarding message to the endpoint : "
+ proxy.getTargetEndpoint());
endpoint.send(synCtx);
} else {
handleException("Unable to find the endpoint specified : " +
proxy.getTargetEndpoint(), synCtx);
}
} else if (proxy.getTargetInLineEndpoint() != null) {
traceOrDebug(traceOn, "Forwarding the message to the anonymous " +
"endpoint of the proxy service");
proxy.getTargetInLineEndpoint().send(synCtx);
}
}
} catch (SynapseException syne) {
if (!synCtx.getFaultStack().isEmpty()) {
warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);
} else {
warn(traceOn, "Exception encountered but no fault handler found - " +
"message dropped", synCtx);
}
}
}
| public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {
boolean traceOn = proxy.getTraceState() == SynapseConstants.TRACING_ON;
boolean traceOrDebugOn = traceOn || log.isDebugEnabled();
String remoteAddr = (String) mc.getProperty(
org.apache.axis2.context.MessageContext.REMOTE_ADDR);
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Proxy Service " + name + " received a new message" +
(remoteAddr != null ? " from : " + remoteAddr : "..."));
traceOrDebug(traceOn, ("Message To: " +
(mc.getTo() != null ? mc.getTo().getAddress() : "null")));
traceOrDebug(traceOn, ("SOAPAction: " +
(mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
traceOrDebug(traceOn, ("WSA-Action: " +
(mc.getWSAAction() != null ? mc.getWSAAction() : "null")));
if (traceOn && trace.isTraceEnabled()) {
String[] cids = mc.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (String cid : cids) {
trace.trace("With attachment content ID : " + cid);
}
}
trace.trace("Envelope : " + mc.getEnvelope());
}
}
MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
// get service log for this message and attach to the message context also set proxy name
Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
((Axis2MessageContext) synCtx).setServiceLog(serviceLog);
synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
synCtx.setTracingState(proxy.getTraceState());
try {
// Setting property to collect the proxy service statistics
boolean statsOn = (SynapseConstants.STATISTICS_ON == proxy.getStatisticsState());
if (statsOn) {
ProxyServiceStatisticsStack proxyServiceStatisticsStack
= new ProxyServiceStatisticsStack();
boolean isFault = synCtx.getEnvelope().getBody().hasFault();
proxyServiceStatisticsStack.put(name, System.currentTimeMillis(),
!synCtx.isResponse(), statsOn, isFault);
synCtx.setProperty(SynapseConstants.PROXY_STATS,
proxyServiceStatisticsStack);
}
// setup fault sequence - i.e. what happens when something goes wrong with this message
if (proxy.getTargetFaultSequence() != null) {
Mediator faultSequence = synCtx.getSequence(proxy.getTargetFaultSequence());
if (faultSequence != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn,
"Setting the fault-sequence to : " + faultSequence);
}
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(proxy.getTargetFaultSequence())));
} else {
// when we can not find the reference to the fault sequence of the proxy
// service we should not throw an exception because still we have the global
// fault sequence and the message mediation can still continue
traceOrDebug(traceOn, "Unable to find fault-sequence : " +
proxy.getTargetFaultSequence() + "; using default fault sequence");
synCtx.pushFaultHandler(new MediatorFaultHandler(
synCtx.getSequence(SynapseConstants.FAULT_SEQUENCE_KEY)));
}
} else if (proxy.getTargetInLineFaultSequence() != null) {
if (traceOrDebugOn) {
traceOrDebug(traceOn, "Setting specified anonymous fault-sequence for proxy");
}
synCtx.pushFaultHandler(
new MediatorFaultHandler(proxy.getTargetInLineFaultSequence()));
}
boolean inSequenceResult = true;
// Using inSequence for the incoming message mediation
if (proxy.getTargetInSequence() != null) {
Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
if (inSequence != null) {
traceOrDebug(traceOn, "Using sequence named : "
+ proxy.getTargetInSequence() + " for incoming message mediation");
inSequenceResult = inSequence.mediate(synCtx);
} else {
handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
}
} else if (proxy.getTargetInLineInSequence() != null) {
traceOrDebug(traceOn, "Using the anonymous " +
"in-sequence of the proxy service for mediation");
inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
}
// if inSequence returns true, forward message to endpoint
if(inSequenceResult) {
if (proxy.getTargetEndpoint() != null) {
Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());
if (endpoint != null) {
traceOrDebug(traceOn, "Forwarding message to the endpoint : "
+ proxy.getTargetEndpoint());
endpoint.send(synCtx);
} else {
handleException("Unable to find the endpoint specified : " +
proxy.getTargetEndpoint(), synCtx);
}
} else if (proxy.getTargetInLineEndpoint() != null) {
traceOrDebug(traceOn, "Forwarding the message to the anonymous " +
"endpoint of the proxy service");
proxy.getTargetInLineEndpoint().send(synCtx);
}
}
} catch (SynapseException syne) {
if (!synCtx.getFaultStack().isEmpty()) {
warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);
} else {
warn(traceOn, "Exception encountered but no fault handler found - " +
"message dropped", synCtx);
}
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
index fdb4cc47b..c49d87028 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorActionContributor.java
@@ -1,434 +1,436 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.ICoolBarManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.mylyn.internal.tasks.core.OrphanedTasksContainer;
import org.eclipse.mylyn.internal.tasks.ui.AddExistingTaskJob;
import org.eclipse.mylyn.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.internal.tasks.ui.actions.AbstractTaskEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.AttachAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.AttachScreenshotAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.NewTaskFromSelectionAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.OpenWithBrowserAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.ShowInTaskListAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.TaskActivateAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.TaskDeactivateAction;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView;
import org.eclipse.mylyn.tasks.core.AbstractTask;
import org.eclipse.mylyn.tasks.core.AbstractTaskCategory;
import org.eclipse.mylyn.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.tasks.ui.editors.AbstractRepositoryTaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.NewTaskEditorInput;
import org.eclipse.mylyn.tasks.ui.editors.RepositoryTaskEditorInput;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskFormPage;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.SubActionBars;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.internal.ObjectActionContributorManager;
import org.eclipse.ui.internal.WorkbenchImages;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
/**
* @author Mik Kersten
* @author Rob Elves
*/
public class TaskEditorActionContributor extends MultiPageEditorActionBarContributor implements
ISelectionChangedListener {
private SubActionBars sourceActionBars;
private TaskEditor editor;
private OpenWithBrowserAction openWithBrowserAction = new OpenWithBrowserAction();
private CopyTaskDetailsAction copyTaskDetailsAction = new CopyTaskDetailsAction(false);
private AbstractTaskEditorAction attachAction = new AttachAction();
private AbstractTaskEditorAction attachScreenshotAction = new AttachScreenshotAction();
private SynchronizeEditorAction synchronizeEditorAction = new SynchronizeEditorAction();
private ShowInTaskListAction showInTaskListAction = new ShowInTaskListAction();
private NewTaskFromSelectionAction newTaskFromSelectionAction = new NewTaskFromSelectionAction();
private GlobalAction cutAction;
private GlobalAction undoAction;
private GlobalAction redoAction;
private GlobalAction copyAction;
private GlobalAction pasteAction;
private GlobalAction selectAllAction;
public TaskEditorActionContributor() {
cutAction = new GlobalAction(ActionFactory.CUT.getId());
cutAction.setText(WorkbenchMessages.Workbench_cut);
cutAction.setToolTipText(WorkbenchMessages.Workbench_cutToolTip);
cutAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
cutAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
cutAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.CUT);
pasteAction = new GlobalAction(ActionFactory.PASTE.getId());
pasteAction.setText(WorkbenchMessages.Workbench_paste);
pasteAction.setToolTipText(WorkbenchMessages.Workbench_pasteToolTip);
pasteAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
pasteAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
pasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
copyAction = new GlobalAction(ActionFactory.COPY.getId());
copyAction.setText(WorkbenchMessages.Workbench_copy);
copyAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
copyAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
copyAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.COPY);
undoAction = new GlobalAction(ActionFactory.UNDO.getId());
undoAction.setText(WorkbenchMessages.Workbench_undo);
undoAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO));
undoAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO));
undoAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_UNDO_DISABLED));
undoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.UNDO);
redoAction = new GlobalAction(ActionFactory.REDO.getId());
redoAction.setText(WorkbenchMessages.Workbench_redo);
redoAction.setImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
redoAction.setHoverImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO));
redoAction.setDisabledImageDescriptor(WorkbenchImages.getImageDescriptor(ISharedImages.IMG_TOOL_REDO_DISABLED));
redoAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.REDO);
selectAllAction = new GlobalAction(ActionFactory.SELECT_ALL.getId());
selectAllAction.setText(WorkbenchMessages.Workbench_selectAll);
selectAllAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.SELECT_ALL);
selectAllAction.setEnabled(true);
}
public void addClipboardActions(IMenuManager manager) {
manager.add(undoAction);
manager.add(redoAction);
manager.add(new Separator());
manager.add(cutAction);
manager.add(copyAction);
manager.add(copyTaskDetailsAction);
manager.add(pasteAction);
manager.add(selectAllAction);
manager.add(newTaskFromSelectionAction);
manager.add(new Separator());
}
public void contextMenuAboutToShow(IMenuManager mng) {
boolean addClipboard = this.getEditor().getActivePageInstance() != null
&& (this.getEditor().getActivePageInstance() instanceof TaskPlanningEditor || this.getEditor()
.getActivePageInstance() instanceof AbstractRepositoryTaskEditor);
contextMenuAboutToShow(mng, addClipboard);
}
public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskCategory> categories = new ArrayList<AbstractTaskCategory>(
TasksUiPlugin.getTaskListManager().getTaskList().getCategories());
Collections.sort(categories);
for (final AbstractTaskCategory category : categories) {
if (!(category instanceof OrphanedTasksContainer)) {//.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final AbstractTask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachAction.selectionChanged(selection);
attachAction.setEditor(editor);
+ attachAction.setEnabled(!task.isLocal());
attachScreenshotAction.selectionChanged(selection);
attachScreenshotAction.setEditor(editor);
+ attachScreenshotAction.setEnabled(!task.isLocal());
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
showInTaskListAction.selectionChanged(selection);
manager.add(new Separator());
manager.add(synchronizeEditorAction);
manager.add(openWithBrowserAction);
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
// TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(showInTaskListAction);
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
if (TaskListView.ID_SEPARATOR_TASKS.equals(menuPath)) {
List<AbstractTaskContainer> selectedElements = new ArrayList<AbstractTaskContainer>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
}
manager.add(new Separator());
manager.add(attachAction);
manager.add(attachScreenshotAction);
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void moveToCategory(AbstractTaskCategory category) {
IEditorInput input = getEditor().getEditorInput();
if (input instanceof RepositoryTaskEditorInput) {
RepositoryTaskEditorInput repositoryTaskEditorInput = (RepositoryTaskEditorInput) input;
final IProgressService svc = PlatformUI.getWorkbench().getProgressService();
final AddExistingTaskJob job = new AddExistingTaskJob(repositoryTaskEditorInput.getRepository(),
repositoryTaskEditorInput.getId(), category);
job.schedule();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
svc.showInDialog(getEditor().getSite().getShell(), job);
}
});
}
}
public void updateSelectableActions(ISelection selection) {
if (editor != null) {
cutAction.selectionChanged(selection);
copyAction.selectionChanged(selection);
pasteAction.selectionChanged(selection);
undoAction.selectionChanged(selection);
redoAction.selectionChanged(selection);
selectAllAction.selectionChanged(selection);
newTaskFromSelectionAction.selectionChanged(selection);
}
}
@Override
public void contributeToMenu(IMenuManager mm) {
}
@Override
public void contributeToStatusLine(IStatusLineManager slm) {
}
@Override
public void contributeToToolBar(IToolBarManager tbm) {
}
@Override
public void contributeToCoolBar(ICoolBarManager cbm) {
}
@Override
public void dispose() {
sourceActionBars.dispose();
super.dispose();
}
@Override
public void init(IActionBars bars) {
super.init(bars);
sourceActionBars = new SubActionBars(bars);
}
@Override
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
registerGlobalHandlers(bars);
}
public TaskEditor getEditor() {
return editor;
}
public IStatusLineManager getStatusLineManager() {
return getActionBars().getStatusLineManager();
}
@Override
public void setActiveEditor(IEditorPart targetEditor) {
if (targetEditor instanceof TaskEditor) {
editor = (TaskEditor) targetEditor;
updateSelectableActions(editor.getSelection());
}
}
@Override
public void setActivePage(IEditorPart newEditor) {
if (getEditor() != null) {
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(SelectionChangedEvent event) {
updateSelectableActions(event.getSelection());
}
private class GlobalAction extends Action {
private String actionId;
public GlobalAction(String actionId) {
this.actionId = actionId;
}
@Override
public void run() {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
editor.doAction(actionId);
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(ISelection selection) {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
setEnabled(editor.canPerformAction(actionId));
}
}
}
public void registerGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), cutAction);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), pasteAction);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), undoAction);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), redoAction);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), selectAllAction);
bars.updateActionBars();
}
public void unregisterGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
bars.updateActionBars();
}
public void forceActionsEnabled() {
cutAction.setEnabled(true);
copyAction.setEnabled(true);
pasteAction.setEnabled(true);
selectAllAction.setEnabled(true);
undoAction.setEnabled(false);
redoAction.setEnabled(false);
}
}
| false | true | public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskCategory> categories = new ArrayList<AbstractTaskCategory>(
TasksUiPlugin.getTaskListManager().getTaskList().getCategories());
Collections.sort(categories);
for (final AbstractTaskCategory category : categories) {
if (!(category instanceof OrphanedTasksContainer)) {//.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final AbstractTask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachAction.selectionChanged(selection);
attachAction.setEditor(editor);
attachScreenshotAction.selectionChanged(selection);
attachScreenshotAction.setEditor(editor);
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
showInTaskListAction.selectionChanged(selection);
manager.add(new Separator());
manager.add(synchronizeEditorAction);
manager.add(openWithBrowserAction);
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
// TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(showInTaskListAction);
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
if (TaskListView.ID_SEPARATOR_TASKS.equals(menuPath)) {
List<AbstractTaskContainer> selectedElements = new ArrayList<AbstractTaskContainer>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
}
manager.add(new Separator());
manager.add(attachAction);
manager.add(attachScreenshotAction);
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void moveToCategory(AbstractTaskCategory category) {
IEditorInput input = getEditor().getEditorInput();
if (input instanceof RepositoryTaskEditorInput) {
RepositoryTaskEditorInput repositoryTaskEditorInput = (RepositoryTaskEditorInput) input;
final IProgressService svc = PlatformUI.getWorkbench().getProgressService();
final AddExistingTaskJob job = new AddExistingTaskJob(repositoryTaskEditorInput.getRepository(),
repositoryTaskEditorInput.getId(), category);
job.schedule();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
svc.showInDialog(getEditor().getSite().getShell(), job);
}
});
}
}
public void updateSelectableActions(ISelection selection) {
if (editor != null) {
cutAction.selectionChanged(selection);
copyAction.selectionChanged(selection);
pasteAction.selectionChanged(selection);
undoAction.selectionChanged(selection);
redoAction.selectionChanged(selection);
selectAllAction.selectionChanged(selection);
newTaskFromSelectionAction.selectionChanged(selection);
}
}
@Override
public void contributeToMenu(IMenuManager mm) {
}
@Override
public void contributeToStatusLine(IStatusLineManager slm) {
}
@Override
public void contributeToToolBar(IToolBarManager tbm) {
}
@Override
public void contributeToCoolBar(ICoolBarManager cbm) {
}
@Override
public void dispose() {
sourceActionBars.dispose();
super.dispose();
}
@Override
public void init(IActionBars bars) {
super.init(bars);
sourceActionBars = new SubActionBars(bars);
}
@Override
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
registerGlobalHandlers(bars);
}
public TaskEditor getEditor() {
return editor;
}
public IStatusLineManager getStatusLineManager() {
return getActionBars().getStatusLineManager();
}
@Override
public void setActiveEditor(IEditorPart targetEditor) {
if (targetEditor instanceof TaskEditor) {
editor = (TaskEditor) targetEditor;
updateSelectableActions(editor.getSelection());
}
}
@Override
public void setActivePage(IEditorPart newEditor) {
if (getEditor() != null) {
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(SelectionChangedEvent event) {
updateSelectableActions(event.getSelection());
}
private class GlobalAction extends Action {
private String actionId;
public GlobalAction(String actionId) {
this.actionId = actionId;
}
@Override
public void run() {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
editor.doAction(actionId);
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(ISelection selection) {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
setEnabled(editor.canPerformAction(actionId));
}
}
}
public void registerGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), cutAction);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), pasteAction);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), undoAction);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), redoAction);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), selectAllAction);
bars.updateActionBars();
}
public void unregisterGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
bars.updateActionBars();
}
public void forceActionsEnabled() {
cutAction.setEnabled(true);
copyAction.setEnabled(true);
pasteAction.setEnabled(true);
selectAllAction.setEnabled(true);
undoAction.setEnabled(false);
redoAction.setEnabled(false);
}
}
| public void contextMenuAboutToShow(IMenuManager manager, boolean addClipboard) {
if (editor != null)
updateSelectableActions(editor.getSelection());
if (addClipboard) {
addClipboardActions(manager);
}
if (editor.getTaskEditorInput() == null && !(editor.getEditorInput() instanceof NewTaskEditorInput)) {
final MenuManager subMenuManager = new MenuManager("Add to " + TaskListView.LABEL_VIEW);
List<AbstractTaskCategory> categories = new ArrayList<AbstractTaskCategory>(
TasksUiPlugin.getTaskListManager().getTaskList().getCategories());
Collections.sort(categories);
for (final AbstractTaskCategory category : categories) {
if (!(category instanceof OrphanedTasksContainer)) {//.equals(TasksUiPlugin.getTaskListManager().getTaskList().getArchiveContainer())) {
Action action = new Action() {
@Override
public void run() {
moveToCategory(category);
}
};
String text = category.getSummary();
action.setText(text);
action.setImageDescriptor(TasksUiImages.CATEGORY);
subMenuManager.add(action);
}
}
copyTaskDetailsAction.selectionChanged(new StructuredSelection(editor.getSelection()));
manager.add(subMenuManager);
return;
} else if (editor.getEditorInput() instanceof NewTaskEditorInput) {
return;
}
final AbstractTask task = editor.getTaskEditorInput().getTask();
if (task == null) {
return;
} else {
// TODO: refactor
IStructuredSelection selection = new StructuredSelection(task);
openWithBrowserAction.selectionChanged(selection);
copyTaskDetailsAction.selectionChanged(selection);
attachAction.selectionChanged(selection);
attachAction.setEditor(editor);
attachAction.setEnabled(!task.isLocal());
attachScreenshotAction.selectionChanged(selection);
attachScreenshotAction.setEditor(editor);
attachScreenshotAction.setEnabled(!task.isLocal());
synchronizeEditorAction.selectionChanged(new StructuredSelection(this.getEditor()));
showInTaskListAction.selectionChanged(selection);
manager.add(new Separator());
manager.add(synchronizeEditorAction);
manager.add(openWithBrowserAction);
if (task.isActive()) {
manager.add(new TaskDeactivateAction() {
@Override
public void run() {
super.run(task);
}
});
} else {
manager.add(new TaskActivateAction() {
@Override
public void run() {
// TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
super.run(task);
}
});
}
manager.add(showInTaskListAction);
manager.add(new Separator());
for (String menuPath : TasksUiPlugin.getDefault().getDynamicMenuMap().keySet()) {
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuMap().get(
menuPath)) {
if (TaskListView.ID_SEPARATOR_TASKS.equals(menuPath)) {
List<AbstractTaskContainer> selectedElements = new ArrayList<AbstractTaskContainer>();
selectedElements.add(task);
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null) {
manager.add(subMenuManager);
}
}
}
}
manager.add(new Separator());
manager.add(attachAction);
manager.add(attachScreenshotAction);
manager.add(new Separator());
// HACK: there should be a saner way of doing this
ObjectActionContributorManager.getManager().contributeObjectActions(editor, manager,
new ISelectionProvider() {
public void addSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public ISelection getSelection() {
return new StructuredSelection(task);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
// ignore
}
public void setSelection(ISelection selection) {
// ignore
}
});
}
manager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void moveToCategory(AbstractTaskCategory category) {
IEditorInput input = getEditor().getEditorInput();
if (input instanceof RepositoryTaskEditorInput) {
RepositoryTaskEditorInput repositoryTaskEditorInput = (RepositoryTaskEditorInput) input;
final IProgressService svc = PlatformUI.getWorkbench().getProgressService();
final AddExistingTaskJob job = new AddExistingTaskJob(repositoryTaskEditorInput.getRepository(),
repositoryTaskEditorInput.getId(), category);
job.schedule();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
svc.showInDialog(getEditor().getSite().getShell(), job);
}
});
}
}
public void updateSelectableActions(ISelection selection) {
if (editor != null) {
cutAction.selectionChanged(selection);
copyAction.selectionChanged(selection);
pasteAction.selectionChanged(selection);
undoAction.selectionChanged(selection);
redoAction.selectionChanged(selection);
selectAllAction.selectionChanged(selection);
newTaskFromSelectionAction.selectionChanged(selection);
}
}
@Override
public void contributeToMenu(IMenuManager mm) {
}
@Override
public void contributeToStatusLine(IStatusLineManager slm) {
}
@Override
public void contributeToToolBar(IToolBarManager tbm) {
}
@Override
public void contributeToCoolBar(ICoolBarManager cbm) {
}
@Override
public void dispose() {
sourceActionBars.dispose();
super.dispose();
}
@Override
public void init(IActionBars bars) {
super.init(bars);
sourceActionBars = new SubActionBars(bars);
}
@Override
public void init(IActionBars bars, IWorkbenchPage page) {
super.init(bars, page);
registerGlobalHandlers(bars);
}
public TaskEditor getEditor() {
return editor;
}
public IStatusLineManager getStatusLineManager() {
return getActionBars().getStatusLineManager();
}
@Override
public void setActiveEditor(IEditorPart targetEditor) {
if (targetEditor instanceof TaskEditor) {
editor = (TaskEditor) targetEditor;
updateSelectableActions(editor.getSelection());
}
}
@Override
public void setActivePage(IEditorPart newEditor) {
if (getEditor() != null) {
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(SelectionChangedEvent event) {
updateSelectableActions(event.getSelection());
}
private class GlobalAction extends Action {
private String actionId;
public GlobalAction(String actionId) {
this.actionId = actionId;
}
@Override
public void run() {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
editor.doAction(actionId);
updateSelectableActions(getEditor().getSelection());
}
}
public void selectionChanged(ISelection selection) {
if (getEditor().getActivePageInstance() instanceof TaskFormPage) {
TaskFormPage editor = (TaskFormPage) getEditor().getActivePageInstance();
setEnabled(editor.canPerformAction(actionId));
}
}
}
public void registerGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), cutAction);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), pasteAction);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), copyAction);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), undoAction);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), redoAction);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), selectAllAction);
bars.updateActionBars();
}
public void unregisterGlobalHandlers(IActionBars bars) {
bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null);
bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null);
bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null);
bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null);
bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
bars.updateActionBars();
}
public void forceActionsEnabled() {
cutAction.setEnabled(true);
copyAction.setEnabled(true);
pasteAction.setEnabled(true);
selectAllAction.setEnabled(true);
undoAction.setEnabled(false);
redoAction.setEnabled(false);
}
}
|
diff --git a/src/com/android/music/MediaPlaybackService.java b/src/com/android/music/MediaPlaybackService.java
index 995a050..f44d5f3 100644
--- a/src/com/android/music/MediaPlaybackService.java
+++ b/src/com/android/music/MediaPlaybackService.java
@@ -1,1853 +1,1853 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.media.MediaFile;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Vector;
/**
* Provides "background" audio playback capabilities, allowing the
* user to switch between activities without stopping playback.
*/
public class MediaPlaybackService extends Service {
/** used to specify whether enqueue() should start playing
* the new list of files right away, next or once all the currently
* queued files have been played
*/
public static final int NOW = 1;
public static final int NEXT = 2;
public static final int LAST = 3;
public static final int PLAYBACKSERVICE_STATUS = 1;
public static final int SHUFFLE_NONE = 0;
public static final int SHUFFLE_NORMAL = 1;
public static final int SHUFFLE_AUTO = 2;
public static final int REPEAT_NONE = 0;
public static final int REPEAT_CURRENT = 1;
public static final int REPEAT_ALL = 2;
public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
public static final String META_CHANGED = "com.android.music.metachanged";
public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
public static final String PLAYBACK_COMPLETE = "com.android.music.playbackcomplete";
public static final String ASYNC_OPEN_COMPLETE = "com.android.music.asyncopencomplete";
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
private static final int TRACK_ENDED = 1;
private static final int RELEASE_WAKELOCK = 2;
private static final int SERVER_DIED = 3;
private static final int FADEIN = 4;
private static final int MAX_HISTORY_SIZE = 10;
private MultiPlayer mPlayer;
private String mFileToPlay;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mMediaMountedCount = 0;
private int [] mAutoShuffleList = null;
private boolean mOneShot;
private int [] mPlayList = null;
private int mPlayListLen = 0;
private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
private Cursor mCursor;
private int mPlayPos = -1;
private static final String LOGTAG = "MediaPlaybackService";
private final Shuffler mRand = new Shuffler();
private int mOpenFailedCounter = 0;
String[] mCursorCols = new String[] {
"audio._id AS _id", // index must match IDCOLIDX below
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below
MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below
};
private final static int IDCOLIDX = 0;
private final static int PODCASTCOLIDX = 8;
private final static int BOOKMARKCOLIDX = 9;
private BroadcastReceiver mUnmountReceiver = null;
private WakeLock mWakeLock;
private int mServiceStartId = -1;
private boolean mServiceInUse = false;
private boolean mResumeAfterCall = false;
private boolean mIsSupposedToBePlaying = false;
private boolean mQuietMode = false;
private SharedPreferences mPreferences;
// We use this to distinguish between different cards when saving/restoring playlists.
// This will have to change if we want to support multiple simultaneous cards.
private int mCardId;
private MediaAppWidgetProvider mAppWidgetProvider = MediaAppWidgetProvider.getInstance();
// interval after which we stop the service when idle
private static final int IDLE_DELAY = 60000;
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int ringvolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
if (ringvolume > 0) {
mResumeAfterCall = (isPlaying() || mResumeAfterCall) && (getAudioId() >= 0);
pause();
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
// pause the music while a conversation is in progress
mResumeAfterCall = (isPlaying() || mResumeAfterCall) && (getAudioId() >= 0);
pause();
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
// start playing again
if (mResumeAfterCall) {
// resume playback only if music was playing
// when the call was answered
startAndFadeIn();
mResumeAfterCall = false;
}
}
}
};
private void startAndFadeIn() {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
}
private Handler mMediaplayerHandler = new Handler() {
float mCurrentVolume = 1.0f;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FADEIN:
if (!isPlaying()) {
mCurrentVolume = 0f;
mPlayer.setVolume(mCurrentVolume);
play();
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
} else {
mCurrentVolume += 0.01f;
if (mCurrentVolume < 1.0f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
} else {
mCurrentVolume = 1.0f;
}
mPlayer.setVolume(mCurrentVolume);
}
break;
case SERVER_DIED:
if (mIsSupposedToBePlaying) {
next(true);
} else {
// the server died when we were idle, so just
// reopen the same song (it will start again
// from the beginning though when the user
// restarts)
openCurrent();
}
break;
case TRACK_ENDED:
if (mRepeatMode == REPEAT_CURRENT) {
seek(0);
play();
} else if (!mOneShot) {
next(false);
} else {
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
}
break;
case RELEASE_WAKELOCK:
mWakeLock.release();
break;
default:
break;
}
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
} else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) {
// Someone asked us to refresh a set of specific widgets, probably
// because they were just added.
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds);
}
}
};
public MediaPlaybackService() {
}
@Override
public void onCreate() {
super.onCreate();
mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
mCardId = FileUtils.getFatVolumeId(Environment.getExternalStorageDirectory().getPath());
registerExternalStorageListener();
// Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
mPlayer = new MultiPlayer();
mPlayer.setHandler(mMediaplayerHandler);
// Clear leftover notification in case this service previously got killed while playing
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
reloadQueue();
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(SERVICECMD);
commandFilter.addAction(TOGGLEPAUSE_ACTION);
commandFilter.addAction(PAUSE_ACTION);
commandFilter.addAction(NEXT_ACTION);
commandFilter.addAction(PREVIOUS_ACTION);
registerReceiver(mIntentReceiver, commandFilter);
TelephonyManager tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tmgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
mWakeLock.setReferenceCounted(false);
// If the service was idle, but got killed before it stopped itself, the
// system will relaunch it. Make sure it gets stopped again in that case.
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public void onDestroy() {
// Check that we're not being destroyed while something is still playing.
if (isPlaying()) {
Log.e("MediaPlaybackService", "Service being destroyed while still playing.");
}
// release all MediaPlayer resources, including the native player and wakelocks
mPlayer.release();
mPlayer = null;
// make sure there aren't any other messages coming
mDelayedStopHandler.removeCallbacksAndMessages(null);
mMediaplayerHandler.removeCallbacksAndMessages(null);
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
TelephonyManager tmgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tmgr.listen(mPhoneStateListener, 0);
unregisterReceiver(mIntentReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
mWakeLock.release();
super.onDestroy();
}
private final char hexdigits [] = new char [] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
private void saveQueue(boolean full) {
if (mOneShot) {
return;
}
Editor ed = mPreferences.edit();
//long start = System.currentTimeMillis();
if (full) {
StringBuilder q = new StringBuilder();
// The current playlist is saved as a list of "reverse hexadecimal"
// numbers, which we can generate faster than normal decimal or
// hexadecimal numbers, which in turn allows us to save the playlist
// more often without worrying too much about performance.
// (saving the full state takes about 40 ms under no-load conditions
// on the phone)
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
int n = mPlayList[i];
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = n & 0xf;
n >>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
//Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms");
ed.putString("queue", q.toString());
ed.putInt("cardid", mCardId);
}
ed.putInt("curpos", mPlayPos);
if (mPlayer.isInitialized()) {
ed.putLong("seekpos", mPlayer.position());
}
ed.putInt("repeatmode", mRepeatMode);
ed.putInt("shufflemode", mShuffleMode);
ed.commit();
//Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms");
}
private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
- int qlen = q.length();
- if (q != null && qlen > 1) {
+ int qlen = q != null ? q.length() : 0;
+ if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 2000) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFileAsync(String path)
{
mService.get().openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
mService.get().open(path, oneShot);
}
public void open(int [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().next(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public int getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public int getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(int [] list , int action) {
mService.get().enqueue(list, action);
}
public int [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public int getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(int id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
}
private final IBinder mBinder = new ServiceStub(this);
}
| true | true | private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q.length();
if (q != null && qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 2000) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFileAsync(String path)
{
mService.get().openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
mService.get().open(path, oneShot);
}
public void open(int [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().next(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public int getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public int getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(int [] list , int action) {
mService.get().enqueue(list, action);
}
public int [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public int getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(int id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
}
private final IBinder mBinder = new ServiceStub(this);
}
| private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 2000) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFileAsync(String path)
{
mService.get().openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
mService.get().open(path, oneShot);
}
public void open(int [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().setQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().stop();
}
public void pause() {
mService.get().pause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().prev();
}
public void next() {
mService.get().next(true);
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public int getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public int getArtistId() {
return mService.get().getArtistId();
}
public void enqueue(int [] list , int action) {
mService.get().enqueue(list, action);
}
public int [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public int getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
return mService.get().seek(pos);
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(int id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
}
private final IBinder mBinder = new ServiceStub(this);
}
|
diff --git a/src/org/jacorb/orb/iiop/ClientIIOPConnection.java b/src/org/jacorb/orb/iiop/ClientIIOPConnection.java
index f45a1594d..750f90bf2 100644
--- a/src/org/jacorb/orb/iiop/ClientIIOPConnection.java
+++ b/src/org/jacorb/orb/iiop/ClientIIOPConnection.java
@@ -1,461 +1,453 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2003 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.orb.iiop;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.avalon.framework.logger.Logger;
import org.jacorb.util.Debug;
import org.jacorb.util.Environment;
import org.jacorb.orb.CDRInputStream;
import org.jacorb.orb.IIOPAddress;
import org.jacorb.orb.factory.SocketFactory;
import org.jacorb.orb.giop.TransportManager;
import org.jacorb.util.Debug;
import org.jacorb.util.Environment;
import org.omg.CSIIOP.CompoundSecMechList;
import org.omg.CSIIOP.CompoundSecMechListHelper;
import org.omg.CSIIOP.Confidentiality;
import org.omg.CSIIOP.DetectMisordering;
import org.omg.CSIIOP.DetectReplay;
import org.omg.CSIIOP.EstablishTrustInClient;
import org.omg.CSIIOP.EstablishTrustInTarget;
import org.omg.CSIIOP.Integrity;
import org.omg.CSIIOP.TAG_CSI_SEC_MECH_LIST;
import org.omg.CSIIOP.TAG_TLS_SEC_TRANS;
import org.omg.CSIIOP.TLS_SEC_TRANS;
import org.omg.CSIIOP.TLS_SEC_TRANSHelper;
import org.omg.SSLIOP.SSL;
import org.omg.SSLIOP.SSLHelper;
import org.omg.SSLIOP.TAG_SSL_SEC_TRANS;
/**
* ClientIIOPConnection.java
*
*
* Created: Sun Aug 12 20:56:32 2002
*
* @author Nicolas Noffke / Andre Spiegel
* @version $Id$
*/
public class ClientIIOPConnection
extends IIOPConnection
{
private IIOPProfile target_profile;
private int timeout = 0;
private boolean use_ssl = false;
private int ssl_port = -1;
private Logger logger = Debug.getNamedLogger("jacorb.iiop.conn");
//for testing purposes only: # of open transports
//used by org.jacorb.test.orb.connection[Client|Server]ConnectionTimeoutTest
public static int openTransports = 0;
public ClientIIOPConnection()
{
super();
//get the client-side timeout property value
String prop =
Environment.getProperty( "jacorb.connection.client.idle_timeout" );
if( prop != null )
{
try
{
timeout = Integer.parseInt( prop );
}
catch( NumberFormatException nfe )
{
if (logger.isErrorEnabled())
{
logger.error("Unable to create int from string >" + prop + "< \n" +
"Please check property \"jacorb.connection.client.idle_timeout\"" );
}
}
}
}
public ClientIIOPConnection (ClientIIOPConnection other)
{
super (other);
this.target_profile = other.target_profile;
this.timeout = other.timeout;
this.use_ssl = other.use_ssl;
this.ssl_port = other.ssl_port;
}
/**
* Attempts to establish a 1-to-1 connection with a server using the
* Listener endpoint from the given Profile description. It shall
* throw a COMM_FAILURE exception if it fails (e.g. if the endpoint
* is unreachable) or a TIMEOUT exception if the given time_out period
* has expired before a connection is established. If the connection
* is successfully established it shall store the used Profile data.
*
*/
public synchronized void connect (org.omg.ETF.Profile server_profile, long time_out)
{
if( ! connected )
{
if (server_profile instanceof IIOPProfile)
{
this.target_profile = (IIOPProfile)server_profile;
}
else
{
throw new org.omg.CORBA.BAD_PARAM
( "attempt to connect an IIOP connection "
+ "to a non-IIOP profile: " + server_profile.getClass());
}
checkSSL();
IIOPAddress address = target_profile.getAddress();
connection_info = address.getIP() + ":"
+ (use_ssl ? ssl_port
: address.getPort());
if (logger.isDebugEnabled())
{
logger.debug("Trying to connect to " + connection_info);
}
int retries = Environment.noOfRetries();
while( retries >= 0 )
{
try
{
socket = createSocket();
if( timeout != 0 )
{
/* re-set the socket timeout */
socket.setSoTimeout( timeout );
}
in_stream =
socket.getInputStream();
out_stream =
new BufferedOutputStream( socket.getOutputStream());
if (logger.isInfoEnabled())
{
logger.info("Connected to " + connection_info +
" from local port " +
socket.getLocalPort() +
( this.isSSL() ? " via SSL" : "" ));
}
connected = true;
//for testing purposes
++openTransports;
return;
}
catch ( IOException c )
{
Debug.output( 3, c );
//only sleep and print message if we're actually
//going to retry
if( retries >= 0 )
{
Debug.output( 1, "Retrying to connect to " +
connection_info );
try
{
Thread.sleep( Environment.retryInterval() );
}
catch( InterruptedException i )
{
}
}
retries--;
}
}
if( retries < 0 )
{
target_profile = null;
use_ssl = false;
ssl_port = -1;
throw new org.omg.CORBA.TRANSIENT
( "Retries exceeded, couldn't reconnect to " +
connection_info );
}
}
}
/**
* Tries to create a socket connection to any of the addresses in
* the target profile, starting with the primary IIOP address,
* and then any alternate IIOP addresses that have been specified.
*/
private Socket createSocket() throws IOException
{
Socket result = null;
IOException exception = null;
List addressList = new ArrayList();
addressList.add (target_profile.getAddress());
addressList.addAll (target_profile.getAlternateAddresses());
Iterator addressIterator = addressList.iterator();
while (result == null && addressIterator.hasNext())
{
try
{
IIOPAddress address = (IIOPAddress)addressIterator.next();
if (use_ssl)
{
result = getSSLSocketFactory().createSocket
(
address.getIP(), ssl_port
);
connection_info = address.getIP() + ":" + ssl_port;
}
else
{
result = getSocketFactory().createSocket
(
address.getIP(), address.getPort()
);
connection_info = address.toString();
}
}
catch (IOException e)
{
exception = e;
}
}
if (result != null)
{
return result;
}
else if (exception != null)
{
throw exception;
}
else
{
throw new IOException ("connection failure without exception");
}
}
public synchronized void close()
{
try
{
if (connected && socket != null)
{
socket.close ();
//this will cause exceptions when trying to read from
//the streams. Better than "nulling" them.
if( in_stream != null )
{
in_stream.close();
}
if( out_stream != null )
{
out_stream.close();
}
//for testing purposes
--openTransports;
}
connected = false;
}
catch (IOException ex)
{
throw to_COMM_FAILURE (ex);
}
if (logger.isInfoEnabled())
{
logger.info("Client-side TCP transport to " +
connection_info + " closed.");
}
}
public boolean isSSL()
{
return use_ssl;
}
public org.omg.ETF.Profile get_server_profile()
{
return target_profile;
}
/**
* Check if this client should use SSL when connecting to
* the server described by the target_profile. The result
* is stored in the private fields use_ssl and ssl_port.
*/
private void checkSSL()
{
CompoundSecMechList sas
= (CompoundSecMechList)target_profile.getComponent
(TAG_CSI_SEC_MECH_LIST.value,
CompoundSecMechListHelper.class);
TLS_SEC_TRANS tls = null;
if (sas != null && sas.mechanism_list[0].transport_mech.tag == TAG_TLS_SEC_TRANS.value) {
try
{
byte[] tagData = sas.mechanism_list[0].transport_mech.component_data;
CDRInputStream in = new CDRInputStream( (org.omg.CORBA.ORB)null, tagData );
in.openEncapsulatedArray();
tls = TLS_SEC_TRANSHelper.read( in );
}
catch ( Exception ex )
{
logger.warn("Error parsing TLS_SEC_TRANS: "+ex);
}
}
SSL ssl = (SSL)target_profile.getComponent
(TAG_SSL_SEC_TRANS.value,
SSLHelper.class);
//if( sas != null &&
// ssl != null )
//{
// ssl.target_requires |= sas.mechanism_list[0].target_requires;
//}
// SSL usage is decided the following way: At least one side
// must require it. Therefore, we first check if it is
// supported by both sides, and then if it is required by at
// least one side. The distinction between
// EstablishTrustInTarget and EstablishTrustInClient is
// handled at the socket factory layer.
//the following is used as a bit mask to check, if any of
//these options are set
int minimum_options =
Integrity.value |
Confidentiality.value |
DetectReplay.value |
DetectMisordering.value |
EstablishTrustInTarget.value |
EstablishTrustInClient.value;
int client_required = 0;
int client_supported = 0;
//only read in the properties if ssl is really supported.
if( Environment.isPropertyOn( "jacorb.security.support_ssl" ))
{
client_required = Environment.getIntProperty
(
"jacorb.security.ssl.client.required_options", 16
);
client_supported = Environment.getIntProperty
(
"jacorb.security.ssl.client.supported_options", 16
);
}
if( tls != null && // server knows about ssl...
((tls.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((tls.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting TLS for connection");
}
use_ssl = true;
ssl_port = tls.addresses[0].port;
if (ssl_port < 0) ssl_port += 65536;
}
- //prevent client policy violation, i.e. opening plain TCP
- //connections when SSL is required
- else if( tls == null && // server doesn't know ssl...
- Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
- ((client_required & minimum_options) != 0)) //...and requires it
- {
- throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires TLS, but server doesn't support it" );
- }
else if( ssl != null && // server knows about ssl...
((ssl.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((ssl.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting SSL for connection");
}
use_ssl = true;
ssl_port = ssl.port;
if (ssl_port < 0)
ssl_port += 65536;
}
//prevent client policy violation, i.e. opening plain TCP
//connections when SSL is required
- else if( ssl == null && // server doesn't know ssl...
+ else if( // server doesn't know ssl...
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_required & minimum_options) != 0)) //...and requires it
{
- throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires SSL, but server doesn't support it" );
+ throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires SSL/TLS, but server doesn't support it" );
}
else
{
use_ssl = false;
ssl_port = -1;
}
}
private SocketFactory getSocketFactory()
{
return TransportManager.socket_factory;
}
private SocketFactory getSSLSocketFactory()
{
return TransportManager.ssl_socket_factory;
}
}// Client_TCP_IP_Transport
| false | true | private void checkSSL()
{
CompoundSecMechList sas
= (CompoundSecMechList)target_profile.getComponent
(TAG_CSI_SEC_MECH_LIST.value,
CompoundSecMechListHelper.class);
TLS_SEC_TRANS tls = null;
if (sas != null && sas.mechanism_list[0].transport_mech.tag == TAG_TLS_SEC_TRANS.value) {
try
{
byte[] tagData = sas.mechanism_list[0].transport_mech.component_data;
CDRInputStream in = new CDRInputStream( (org.omg.CORBA.ORB)null, tagData );
in.openEncapsulatedArray();
tls = TLS_SEC_TRANSHelper.read( in );
}
catch ( Exception ex )
{
logger.warn("Error parsing TLS_SEC_TRANS: "+ex);
}
}
SSL ssl = (SSL)target_profile.getComponent
(TAG_SSL_SEC_TRANS.value,
SSLHelper.class);
//if( sas != null &&
// ssl != null )
//{
// ssl.target_requires |= sas.mechanism_list[0].target_requires;
//}
// SSL usage is decided the following way: At least one side
// must require it. Therefore, we first check if it is
// supported by both sides, and then if it is required by at
// least one side. The distinction between
// EstablishTrustInTarget and EstablishTrustInClient is
// handled at the socket factory layer.
//the following is used as a bit mask to check, if any of
//these options are set
int minimum_options =
Integrity.value |
Confidentiality.value |
DetectReplay.value |
DetectMisordering.value |
EstablishTrustInTarget.value |
EstablishTrustInClient.value;
int client_required = 0;
int client_supported = 0;
//only read in the properties if ssl is really supported.
if( Environment.isPropertyOn( "jacorb.security.support_ssl" ))
{
client_required = Environment.getIntProperty
(
"jacorb.security.ssl.client.required_options", 16
);
client_supported = Environment.getIntProperty
(
"jacorb.security.ssl.client.supported_options", 16
);
}
if( tls != null && // server knows about ssl...
((tls.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((tls.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting TLS for connection");
}
use_ssl = true;
ssl_port = tls.addresses[0].port;
if (ssl_port < 0) ssl_port += 65536;
}
//prevent client policy violation, i.e. opening plain TCP
//connections when SSL is required
else if( tls == null && // server doesn't know ssl...
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_required & minimum_options) != 0)) //...and requires it
{
throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires TLS, but server doesn't support it" );
}
else if( ssl != null && // server knows about ssl...
((ssl.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((ssl.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting SSL for connection");
}
use_ssl = true;
ssl_port = ssl.port;
if (ssl_port < 0)
ssl_port += 65536;
}
//prevent client policy violation, i.e. opening plain TCP
//connections when SSL is required
else if( ssl == null && // server doesn't know ssl...
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_required & minimum_options) != 0)) //...and requires it
{
throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires SSL, but server doesn't support it" );
}
else
{
use_ssl = false;
ssl_port = -1;
}
}
| private void checkSSL()
{
CompoundSecMechList sas
= (CompoundSecMechList)target_profile.getComponent
(TAG_CSI_SEC_MECH_LIST.value,
CompoundSecMechListHelper.class);
TLS_SEC_TRANS tls = null;
if (sas != null && sas.mechanism_list[0].transport_mech.tag == TAG_TLS_SEC_TRANS.value) {
try
{
byte[] tagData = sas.mechanism_list[0].transport_mech.component_data;
CDRInputStream in = new CDRInputStream( (org.omg.CORBA.ORB)null, tagData );
in.openEncapsulatedArray();
tls = TLS_SEC_TRANSHelper.read( in );
}
catch ( Exception ex )
{
logger.warn("Error parsing TLS_SEC_TRANS: "+ex);
}
}
SSL ssl = (SSL)target_profile.getComponent
(TAG_SSL_SEC_TRANS.value,
SSLHelper.class);
//if( sas != null &&
// ssl != null )
//{
// ssl.target_requires |= sas.mechanism_list[0].target_requires;
//}
// SSL usage is decided the following way: At least one side
// must require it. Therefore, we first check if it is
// supported by both sides, and then if it is required by at
// least one side. The distinction between
// EstablishTrustInTarget and EstablishTrustInClient is
// handled at the socket factory layer.
//the following is used as a bit mask to check, if any of
//these options are set
int minimum_options =
Integrity.value |
Confidentiality.value |
DetectReplay.value |
DetectMisordering.value |
EstablishTrustInTarget.value |
EstablishTrustInClient.value;
int client_required = 0;
int client_supported = 0;
//only read in the properties if ssl is really supported.
if( Environment.isPropertyOn( "jacorb.security.support_ssl" ))
{
client_required = Environment.getIntProperty
(
"jacorb.security.ssl.client.required_options", 16
);
client_supported = Environment.getIntProperty
(
"jacorb.security.ssl.client.supported_options", 16
);
}
if( tls != null && // server knows about ssl...
((tls.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((tls.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting TLS for connection");
}
use_ssl = true;
ssl_port = tls.addresses[0].port;
if (ssl_port < 0) ssl_port += 65536;
}
else if( ssl != null && // server knows about ssl...
((ssl.target_supports & minimum_options) != 0) && //...and "really" supports it
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_supported & minimum_options) != 0 )&& //...and "really" supports it
( ((ssl.target_requires & minimum_options) != 0) || //server ...
((client_required & minimum_options) != 0))) //...or client require it
{
if (logger.isDebugEnabled())
{
logger.debug("Selecting SSL for connection");
}
use_ssl = true;
ssl_port = ssl.port;
if (ssl_port < 0)
ssl_port += 65536;
}
//prevent client policy violation, i.e. opening plain TCP
//connections when SSL is required
else if( // server doesn't know ssl...
Environment.isPropertyOn( "jacorb.security.support_ssl" ) && //client knows about ssl...
((client_required & minimum_options) != 0)) //...and requires it
{
throw new org.omg.CORBA.NO_PERMISSION( "Client-side policy requires SSL/TLS, but server doesn't support it" );
}
else
{
use_ssl = false;
ssl_port = -1;
}
}
|
diff --git a/src/org/openstreetmap/josm/tools/WikiReader.java b/src/org/openstreetmap/josm/tools/WikiReader.java
index 1c57d7c2..8a20457a 100644
--- a/src/org/openstreetmap/josm/tools/WikiReader.java
+++ b/src/org/openstreetmap/josm/tools/WikiReader.java
@@ -1,75 +1,77 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
/**
* Read a trac-wiki page.
*
* @author imi
*/
public class WikiReader {
public static final String JOSM_EXTERN = "http://josm-extern.";
private final String baseurl;
public WikiReader(String baseurl) {
this.baseurl = baseurl;
}
/**
* Read the page specified by the url and return the content.
*
* If the url is within the baseurl path, parse it as an trac wikipage and
* replace relative pathes etc..
*
* @return Either the string of the content of the wiki page.
* @throws IOException Throws, if the page could not be loaded.
*/
public String read(String url) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "utf-8"));
if (url.startsWith(baseurl) && !url.endsWith("?format=txt"))
return readFromTrac(in, url);
return readNormal(in);
}
private String readNormal(BufferedReader in) throws IOException {
StringBuilder b = new StringBuilder("<html>");
for (String line = in.readLine(); line != null; line = in.readLine()) {
line = adjustText(line);
b.append(line);
b.append("\n");
}
return b.toString();
}
private String readFromTrac(BufferedReader in, String url) throws IOException {
boolean inside = false;
StringBuilder b = new StringBuilder("<html>");
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (line.contains("<div id=\"searchable\">"))
inside = true;
+ else if (line.contains("<div class=\"wikipage searchable\">"))
+ inside = true;
else if (line.contains("<div class=\"buttons\">"))
inside = false;
if (inside) {
line = line.replaceAll("<img src=\"/", "<img src=\""+baseurl+"/");
line = line.replaceAll("href=\"/", "href=\""+baseurl+"/");
if (!line.contains("$"))
line = line.replaceAll("<p>Describe \"([^\"]+)\" here</p>", "<p>Describe \"$1\" <a href=\""+JOSM_EXTERN+url.substring(7)+"\">here</a></p>");
line = adjustText(line);
b.append(line);
b.append("\n");
}
}
b.append("</html>");
return b.toString();
}
private String adjustText(String text) {
text = text.replaceAll(" />", ">");
return text;
}
}
| true | true | private String readFromTrac(BufferedReader in, String url) throws IOException {
boolean inside = false;
StringBuilder b = new StringBuilder("<html>");
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (line.contains("<div id=\"searchable\">"))
inside = true;
else if (line.contains("<div class=\"buttons\">"))
inside = false;
if (inside) {
line = line.replaceAll("<img src=\"/", "<img src=\""+baseurl+"/");
line = line.replaceAll("href=\"/", "href=\""+baseurl+"/");
if (!line.contains("$"))
line = line.replaceAll("<p>Describe \"([^\"]+)\" here</p>", "<p>Describe \"$1\" <a href=\""+JOSM_EXTERN+url.substring(7)+"\">here</a></p>");
line = adjustText(line);
b.append(line);
b.append("\n");
}
}
b.append("</html>");
return b.toString();
}
| private String readFromTrac(BufferedReader in, String url) throws IOException {
boolean inside = false;
StringBuilder b = new StringBuilder("<html>");
for (String line = in.readLine(); line != null; line = in.readLine()) {
if (line.contains("<div id=\"searchable\">"))
inside = true;
else if (line.contains("<div class=\"wikipage searchable\">"))
inside = true;
else if (line.contains("<div class=\"buttons\">"))
inside = false;
if (inside) {
line = line.replaceAll("<img src=\"/", "<img src=\""+baseurl+"/");
line = line.replaceAll("href=\"/", "href=\""+baseurl+"/");
if (!line.contains("$"))
line = line.replaceAll("<p>Describe \"([^\"]+)\" here</p>", "<p>Describe \"$1\" <a href=\""+JOSM_EXTERN+url.substring(7)+"\">here</a></p>");
line = adjustText(line);
b.append(line);
b.append("\n");
}
}
b.append("</html>");
return b.toString();
}
|
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java
index 375529f2..abe6bdd0 100644
--- a/java/src/com/android/inputmethod/latin/LatinIME.java
+++ b/java/src/com/android/inputmethod/latin/LatinIME.java
@@ -1,2243 +1,2244 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.compat.CompatUtils;
import com.android.inputmethod.compat.EditorInfoCompatUtils;
import com.android.inputmethod.compat.InputConnectionCompatUtils;
import com.android.inputmethod.compat.InputMethodManagerCompatWrapper;
import com.android.inputmethod.compat.InputMethodServiceCompatWrapper;
import com.android.inputmethod.compat.InputTypeCompatUtils;
import com.android.inputmethod.compat.VibratorCompatWrapper;
import com.android.inputmethod.deprecated.LanguageSwitcherProxy;
import com.android.inputmethod.deprecated.VoiceProxy;
import com.android.inputmethod.keyboard.Keyboard;
import com.android.inputmethod.keyboard.KeyboardActionListener;
import com.android.inputmethod.keyboard.KeyboardSwitcher;
import com.android.inputmethod.keyboard.KeyboardView;
import com.android.inputmethod.keyboard.LatinKeyboard;
import com.android.inputmethod.keyboard.LatinKeyboardView;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.inputmethodservice.InputMethodService;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.InputConnection;
import android.widget.LinearLayout;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Locale;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener {
private static final String TAG = LatinIME.class.getSimpleName();
private static final boolean PERF_DEBUG = false;
private static final boolean TRACE = false;
private static boolean DEBUG = LatinImeLogger.sDBG;
/**
* The private IME option used to indicate that no microphone should be
* shown for a given text field. For instance, this is specified by the
* search dialog when the dialog is already showing a voice search button.
*
* @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed.
*/
@SuppressWarnings("dep-ann")
public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm";
/**
* The private IME option used to indicate that no microphone should be
* shown for a given text field. For instance, this is specified by the
* search dialog when the dialog is already showing a voice search button.
*/
public static final String IME_OPTION_NO_MICROPHONE = "noMicrophoneKey";
/**
* The private IME option used to indicate that no settings key should be
* shown for a given text field.
*/
public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey";
private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
/**
* The name of the scheme used by the Package Manager to warn of a new package installation,
* replacement or removal.
*/
private static final String SCHEME_PACKAGE = "package";
private int mSuggestionVisibility;
private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE
= R.string.prefs_suggestion_visibility_show_value;
private static final int SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE
= R.string.prefs_suggestion_visibility_show_only_portrait_value;
private static final int SUGGESTION_VISIBILILTY_HIDE_VALUE
= R.string.prefs_suggestion_visibility_hide_value;
private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] {
SUGGESTION_VISIBILILTY_SHOW_VALUE,
SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE,
SUGGESTION_VISIBILILTY_HIDE_VALUE
};
private View mCandidateViewContainer;
private int mCandidateStripHeight;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mApplicationSpecifiedCompletions;
private AlertDialog mOptionsDialog;
private InputMethodManagerCompatWrapper mImm;
private Resources mResources;
private SharedPreferences mPrefs;
private String mInputMethodId;
private KeyboardSwitcher mKeyboardSwitcher;
private SubtypeSwitcher mSubtypeSwitcher;
private VoiceProxy mVoiceProxy;
private Recorrection mRecorrection;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
// TODO: Create an inner class to group options and pseudo-options to improve readability.
// These variables are initialized according to the {@link EditorInfo#inputType}.
private boolean mShouldInsertMagicSpace;
private boolean mInputTypeNoAutoCorrect;
private boolean mIsSettingsSuggestionStripOn;
private boolean mApplicationSpecifiedCompletionOn;
private AccessibilityUtils mAccessibilityUtils;
private final StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private CharSequence mBestWord;
private boolean mHasUncommittedTypedChars;
private boolean mHasDictionary;
// Magic space: a space that should disappear on space/apostrophe insertion, move after the
// punctuation on punctuation insertion, and become a real space on alpha char insertion.
private boolean mJustAddedMagicSpace; // This indicates whether the last char is a magic space.
private boolean mAutoCorrectEnabled;
// Suggestion: use bigrams to adjust scores of suggestions obtained from unigram dictionary
private boolean mBigramSuggestionEnabled;
// Prediction: use bigrams to predict the next word when there is no input for it yet
private boolean mBigramPredictionEnabled;
private boolean mAutoCorrectOn;
private boolean mVibrateOn;
private boolean mSoundOn;
private boolean mPopupOn;
private boolean mAutoCap;
private boolean mQuickFixes;
private boolean mConfigEnableShowSubtypeSettings;
private boolean mConfigSwipeDownDismissKeyboardEnabled;
private int mConfigDelayBeforeFadeoutLanguageOnSpacebar;
private int mConfigDelayUpdateSuggestions;
private int mConfigDelayUpdateOldSuggestions;
private int mConfigDelayUpdateShiftState;
private int mConfigDurationOfFadeoutLanguageOnSpacebar;
private float mConfigFinalFadeoutFactorOfLanguageOnSpacebar;
private long mConfigDoubleSpacesTurnIntoPeriodTimeout;
private int mCorrectionMode;
private int mCommittedLength;
private int mOrientation;
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
private SuggestedWords mSuggestPuncList;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private int mDeleteCount;
private long mLastKeyTime;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private static final float FX_VOLUME = -1.0f;
private boolean mSilentMode;
/* package */ String mWordSeparators;
private String mMagicSpaceStrippers;
private String mMagicSpaceSwappers;
private String mSuggestPuncs;
// TODO: Move this flag to VoiceProxy
private boolean mConfigurationChanging;
// Object for reacting to adding/removing a dictionary pack.
private BroadcastReceiver mDictionaryPackInstallReceiver =
new DictionaryPackInstallBroadcastReceiver(this);
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
public final UIHandler mHandler = new UIHandler();
public class UIHandler extends Handler {
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 4;
private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 5;
private static final int MSG_SPACE_TYPED = 6;
private static final int MSG_SET_BIGRAM_PREDICTIONS = 7;
@Override
public void handleMessage(Message msg) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
final LatinKeyboardView inputView = switcher.getInputView();
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
mRecorrection.setRecorrectionSuggestions(mVoiceProxy, mCandidateView, mSuggest,
mKeyboardSwitcher, mWord, mHasUncommittedTypedChars, mLastSelectionStart,
mLastSelectionEnd, mWordSeparators);
break;
case MSG_UPDATE_SHIFT_STATE:
switcher.updateShiftState();
break;
case MSG_SET_BIGRAM_PREDICTIONS:
updateBigramPredictions();
break;
case MSG_VOICE_RESULTS:
mVoiceProxy.handleVoiceResults(preferCapitalization()
|| (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked()));
break;
case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR:
if (inputView != null)
inputView.setSpacebarTextFadeFactor(
(1.0f + mConfigFinalFadeoutFactorOfLanguageOnSpacebar) / 2,
(LatinKeyboard)msg.obj);
sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj),
mConfigDurationOfFadeoutLanguageOnSpacebar);
break;
case MSG_DISMISS_LANGUAGE_ON_SPACEBAR:
if (inputView != null)
inputView.setSpacebarTextFadeFactor(
mConfigFinalFadeoutFactorOfLanguageOnSpacebar, (LatinKeyboard)msg.obj);
break;
}
}
public void postUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTIONS);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS),
mConfigDelayUpdateSuggestions);
}
public void cancelUpdateSuggestions() {
removeMessages(MSG_UPDATE_SUGGESTIONS);
}
public boolean hasPendingUpdateSuggestions() {
return hasMessages(MSG_UPDATE_SUGGESTIONS);
}
public void postUpdateOldSuggestions() {
removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
sendMessageDelayed(obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS),
mConfigDelayUpdateOldSuggestions);
}
public void cancelUpdateOldSuggestions() {
removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
}
public void postUpdateShiftKeyState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mConfigDelayUpdateShiftState);
}
public void cancelUpdateShiftState() {
removeMessages(MSG_UPDATE_SHIFT_STATE);
}
public void postUpdateBigramPredictions() {
removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS),
mConfigDelayUpdateSuggestions);
}
public void cancelUpdateBigramPredictions() {
removeMessages(MSG_SET_BIGRAM_PREDICTIONS);
}
public void updateVoiceResults() {
sendMessage(obtainMessage(MSG_VOICE_RESULTS));
}
public void startDisplayLanguageOnSpacebar(boolean localeChanged) {
removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR);
removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR);
final LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
final LatinKeyboard keyboard = mKeyboardSwitcher.getLatinKeyboard();
// The language is always displayed when the delay is negative.
final boolean needsToDisplayLanguage = localeChanged
|| mConfigDelayBeforeFadeoutLanguageOnSpacebar < 0;
// The language is never displayed when the delay is zero.
if (mConfigDelayBeforeFadeoutLanguageOnSpacebar != 0)
inputView.setSpacebarTextFadeFactor(needsToDisplayLanguage ? 1.0f
: mConfigFinalFadeoutFactorOfLanguageOnSpacebar, keyboard);
// The fadeout animation will start when the delay is positive.
if (localeChanged && mConfigDelayBeforeFadeoutLanguageOnSpacebar > 0) {
sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard),
mConfigDelayBeforeFadeoutLanguageOnSpacebar);
}
}
}
public void startDoubleSpacesTimer() {
removeMessages(MSG_SPACE_TYPED);
sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED),
mConfigDoubleSpacesTurnIntoPeriodTimeout);
}
public void cancelDoubleSpacesTimer() {
removeMessages(MSG_SPACE_TYPED);
}
public boolean isAcceptingDoubleSpaces() {
return hasMessages(MSG_SPACE_TYPED);
}
}
@Override
public void onCreate() {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mPrefs = prefs;
LatinImeLogger.init(this, prefs);
LanguageSwitcherProxy.init(this, prefs);
SubtypeSwitcher.init(this, prefs);
KeyboardSwitcher.init(this, prefs);
AccessibilityUtils.init(this, prefs);
Recorrection.init(this, prefs);
super.onCreate();
mImm = InputMethodManagerCompatWrapper.getInstance(this);
mInputMethodId = Utils.getInputMethodId(mImm, getPackageName());
mSubtypeSwitcher = SubtypeSwitcher.getInstance();
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mAccessibilityUtils = AccessibilityUtils.getInstance();
mRecorrection = Recorrection.getInstance();
final Resources res = getResources();
mResources = res;
mConfigEnableShowSubtypeSettings = res.getBoolean(
R.bool.config_enable_show_subtype_settings);
mConfigSwipeDownDismissKeyboardEnabled = res.getBoolean(
R.bool.config_swipe_down_dismiss_keyboard_enabled);
mConfigDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger(
R.integer.config_delay_before_fadeout_language_on_spacebar);
mConfigDelayUpdateSuggestions = res.getInteger(R.integer.config_delay_update_suggestions);
mConfigDelayUpdateOldSuggestions = res.getInteger(
R.integer.config_delay_update_old_suggestions);
mConfigDelayUpdateShiftState = res.getInteger(R.integer.config_delay_update_shift_state);
mConfigDurationOfFadeoutLanguageOnSpacebar = res.getInteger(
R.integer.config_duration_of_fadeout_language_on_spacebar);
mConfigFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger(
R.integer.config_final_fadeout_percentage_of_language_on_spacebar) / 100.0f;
mConfigDoubleSpacesTurnIntoPeriodTimeout = res.getInteger(
R.integer.config_double_spaces_turn_into_period_timeout);
Utils.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest();
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e);
}
}
mOrientation = res.getConfiguration().orientation;
initSuggestPuncList();
// Register to receive ringer mode change and network state change.
// Also receive installation and removal of a dictionary pack.
final IntentFilter filter = new IntentFilter();
filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
mVoiceProxy = VoiceProxy.init(this, prefs, mHandler);
final IntentFilter packageFilter = new IntentFilter();
packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
packageFilter.addDataScheme(SCHEME_PACKAGE);
registerReceiver(mDictionaryPackInstallReceiver, packageFilter);
final IntentFilter newDictFilter = new IntentFilter();
newDictFilter.addAction(
DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION);
registerReceiver(mDictionaryPackInstallReceiver, newDictFilter);
}
private void initSuggest() {
final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
final Locale keyboardLocale = new Locale(localeStr);
final Resources res = mResources;
final Locale savedLocale = Utils.setSystemLocale(res, keyboardLocale);
if (mSuggest != null) {
mSuggest.close();
}
final SharedPreferences prefs = mPrefs;
mQuickFixes = isQuickFixesEnabled(prefs);
int mainDicResId = Utils.getMainDictionaryResourceId(res);
mSuggest = new Suggest(this, mainDicResId, keyboardLocale);
loadAndSetAutoCorrectionThreshold(prefs);
updateAutoTextEnabled();
mUserDictionary = new UserDictionary(this, localeStr);
mSuggest.setUserDictionary(mUserDictionary);
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
mSuggest.setContactsDictionary(mContactsDictionary);
mAutoDictionary = new AutoDictionary(this, this, localeStr, Suggest.DIC_AUTO);
mSuggest.setAutoDictionary(mAutoDictionary);
mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
updateCorrectionMode();
mMagicSpaceStrippers = res.getString(R.string.magic_space_stripping_symbols);
mMagicSpaceSwappers = res.getString(R.string.magic_space_swapping_symbols);
String wordSeparators = mMagicSpaceStrippers + mMagicSpaceSwappers
+ res.getString(R.string.magic_space_promoting_symbols);
final String notWordSeparators = res.getString(R.string.non_word_separator_symbols);
for (int i = notWordSeparators.length() - 1; i >= 0; --i)
wordSeparators = wordSeparators.replace(notWordSeparators.substring(i, i + 1), "");
mWordSeparators = wordSeparators;
Utils.setSystemLocale(res, savedLocale);
}
/* package private */ void resetSuggestMainDict() {
final String localeStr = mSubtypeSwitcher.getInputLocaleStr();
final Locale keyboardLocale = new Locale(localeStr);
int mainDicResId = Utils.getMainDictionaryResourceId(mResources);
mSuggest.resetMainDict(this, mainDicResId, keyboardLocale);
}
@Override
public void onDestroy() {
if (mSuggest != null) {
mSuggest.close();
mSuggest = null;
}
unregisterReceiver(mReceiver);
unregisterReceiver(mDictionaryPackInstallReceiver);
mVoiceProxy.destroy();
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
mSubtypeSwitcher.onConfigurationChanged(conf);
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
if (isShowingOptionDialog())
mOptionsDialog.dismiss();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
mVoiceProxy.onConfigurationChanged(conf);
mConfigurationChanging = false;
// This will work only when the subtype is not supported.
LanguageSwitcherProxy.onConfigurationChanged(conf);
}
@Override
public View onCreateInputView() {
return mKeyboardSwitcher.onCreateInputView();
}
@Override
public View onCreateCandidatesView() {
LayoutInflater inflater = getLayoutInflater();
LinearLayout container = (LinearLayout)inflater.inflate(R.layout.candidates, null);
mCandidateViewContainer = container;
mCandidateStripHeight = (int)mResources.getDimension(R.dimen.candidate_strip_height);
mCandidateView = (CandidateView) container.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return container;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
final KeyboardSwitcher switcher = mKeyboardSwitcher;
LatinKeyboardView inputView = switcher.getInputView();
if (DEBUG) {
Log.d(TAG, "onStartInputView: " + inputView);
}
// In landscape mode, this method gets called without the input view being created.
if (inputView == null) {
return;
}
mSubtypeSwitcher.updateParametersOnStartInputView();
TextEntryState.reset();
// Most such things we decide below in initializeInputAttributesAndGetMode, but we need to
// know now whether this is a password text field, because we need to know now whether we
// want to enable the voice button.
final VoiceProxy voiceIme = mVoiceProxy;
voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(attribute.inputType)
|| InputTypeCompatUtils.isVisiblePasswordInputType(attribute.inputType));
initializeInputAttributes(attribute);
inputView.closing();
mEnteredText = null;
mComposing.setLength(0);
mHasUncommittedTypedChars = false;
mDeleteCount = 0;
mJustAddedMagicSpace = false;
loadSettings(attribute);
if (mSubtypeSwitcher.isKeyboardMode()) {
switcher.loadKeyboard(attribute,
mSubtypeSwitcher.isShortcutImeEnabled() && voiceIme.isVoiceButtonEnabled(),
voiceIme.isVoiceButtonOnPrimary());
switcher.updateShiftState();
}
setCandidatesViewShownInternal(isCandidateStripVisible(), false /* needsInputViewShown */ );
// Delay updating suggestions because keyboard input view may not be shown at this point.
mHandler.postUpdateSuggestions();
updateCorrectionMode();
final boolean accessibilityEnabled = mAccessibilityUtils.isAccessibilityEnabled();
inputView.setKeyPreviewEnabled(mPopupOn);
inputView.setProximityCorrectionEnabled(true);
inputView.setAccessibilityEnabled(accessibilityEnabled);
// If we just entered a text field, maybe it has some old text that requires correction
mRecorrection.checkRecorrectionOnStart();
inputView.setForeground(true);
voiceIme.onStartInputView(inputView.getWindowToken());
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
private void initializeInputAttributes(EditorInfo attribute) {
if (attribute == null)
return;
final int inputType = attribute.inputType;
final int variation = inputType & InputType.TYPE_MASK_VARIATION;
mShouldInsertMagicSpace = false;
mInputTypeNoAutoCorrect = false;
mIsSettingsSuggestionStripOn = false;
mApplicationSpecifiedCompletionOn = false;
mApplicationSpecifiedCompletions = null;
if ((inputType & InputType.TYPE_MASK_CLASS) == InputType.TYPE_CLASS_TEXT) {
mIsSettingsSuggestionStripOn = true;
// Make sure that passwords are not displayed in candidate view
if (InputTypeCompatUtils.isPasswordInputType(inputType)
|| InputTypeCompatUtils.isVisiblePasswordInputType(inputType)) {
mIsSettingsSuggestionStripOn = false;
}
if (InputTypeCompatUtils.isEmailVariation(variation)
|| variation == InputType.TYPE_TEXT_VARIATION_PERSON_NAME) {
mShouldInsertMagicSpace = false;
} else {
mShouldInsertMagicSpace = true;
}
if (InputTypeCompatUtils.isEmailVariation(variation)) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_URI) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_FILTER) {
mIsSettingsSuggestionStripOn = false;
} else if (variation == InputType.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((inputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mIsSettingsSuggestionStripOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0
&& (inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((inputType & InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mIsSettingsSuggestionStripOn = false;
mApplicationSpecifiedCompletionOn = isFullscreenMode();
}
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
mKeyboardSwitcher.onAutoCorrectionStateChanged(false);
mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging);
KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) inputView.closing();
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onFinishInputView(boolean finishingInput) {
super.onFinishInputView(finishingInput);
KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) inputView.setForeground(false);
// Remove pending messages related to update suggestions
mHandler.cancelUpdateSuggestions();
mHandler.cancelUpdateOldSuggestions();
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
mVoiceProxy.showPunctuationHintIfNecessary();
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", lss=" + mLastSelectionStart
+ ", lse=" + mLastSelectionEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart);
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
final boolean selectionChanged = (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart;
final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1;
if (((mComposing.length() > 0 && mHasUncommittedTypedChars)
|| mVoiceProxy.isVoiceInputHighlighted())
&& (selectionChanged || candidatesCleared)) {
if (candidatesCleared) {
// If the composing span has been cleared, save the typed word in the history for
// recorrection before we reset the candidate strip. Then, we'll be able to show
// suggestions for recorrection right away.
mRecorrection.saveWordInHistory(mWord, mComposing);
}
mComposing.setLength(0);
mHasUncommittedTypedChars = false;
if (isCursorTouchingWord()) {
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
} else {
setPunctuationSuggestions();
}
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceProxy.setVoiceInputHighlighted(false);
} else if (!mHasUncommittedTypedChars && !mJustAccepted) {
if (TextEntryState.isAcceptedDefault() || TextEntryState.isSpaceAfterPicked()) {
if (TextEntryState.isAcceptedDefault())
TextEntryState.reset();
mJustAddedMagicSpace = false; // The user moved the cursor.
}
}
mJustAccepted = false;
mHandler.postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
mRecorrection.updateRecorrectionSelection(mKeyboardSwitcher,
mCandidateView, candidatesStart, candidatesEnd, newSelStart,
newSelEnd, oldSelStart, mLastSelectionStart,
mLastSelectionEnd, mHasUncommittedTypedChars);
}
public void setLastSelection(int start, int end) {
mLastSelectionStart = start;
mLastSelectionEnd = end;
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the candidates view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mRecorrection.isRecorrectionEnabled() && isSuggestionsRequested()) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
mKeyboardSwitcher.onAutoCorrectionStateChanged(false);
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
mVoiceProxy.hideVoiceWindow(mConfigurationChanging);
mRecorrection.clearWordsInHistory();
super.hideWindow();
}
@Override
public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) {
if (DEBUG) {
Log.i(TAG, "Received completions:");
if (applicationSpecifiedCompletions != null) {
for (int i = 0; i < applicationSpecifiedCompletions.length; i++) {
Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]);
}
}
}
if (mApplicationSpecifiedCompletionOn) {
mApplicationSpecifiedCompletions = applicationSpecifiedCompletions;
if (applicationSpecifiedCompletions == null) {
clearSuggestions();
return;
}
SuggestedWords.Builder builder = new SuggestedWords.Builder()
.setApplicationSpecifiedCompletions(applicationSpecifiedCompletions)
.setTypedWordValid(true)
.setHasMinimalSuggestion(true);
// When in fullscreen mode, show completions generated by the application
setSuggestions(builder.build());
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
// TODO: Modify this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
final boolean shouldShowCandidates = shown
&& (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true);
if (isExtractViewShown()) {
// No need to have extra space to show the key preview.
mCandidateViewContainer.setMinimumHeight(0);
super.setCandidatesViewShown(shown);
} else {
// We must control the visibility of the suggestion strip in order to avoid clipped
// key previews, even when we don't show the suggestion strip.
mCandidateViewContainer.setVisibility(
shouldShowCandidates ? View.VISIBLE : View.INVISIBLE);
super.setCandidatesViewShown(true);
}
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
final KeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView == null)
return;
final int containerHeight = mCandidateViewContainer.getHeight();
int touchY = containerHeight;
// Need to set touchable region only if input view is being shown
if (mKeyboardSwitcher.isInputViewShown()) {
if (mCandidateViewContainer.getVisibility() == View.VISIBLE) {
touchY -= mCandidateStripHeight;
}
final int touchWidth = inputView.getWidth();
final int touchHeight = inputView.getHeight() + containerHeight
// Extend touchable region below the keyboard.
+ EXTENDED_TOUCHABLE_REGION_HEIGHT;
if (DEBUG) {
Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth
+ " height=" + touchHeight);
}
setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight);
}
outInsets.contentTopInsets = touchY;
outInsets.visibleTopInsets = touchY;
}
@Override
public boolean onEvaluateFullscreenMode() {
final Resources res = mResources;
DisplayMetrics dm = res.getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen mode
float dimen = res.getDimension(R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
}
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// Enable shift key and DPAD to do selections
if (mKeyboardSwitcher.isInputViewShown()
&& mKeyboardSwitcher.isShiftedOrShiftLocked()) {
KeyEvent newEvent = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null)
ic.sendKeyEvent(newEvent);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
public void commitTyped(InputConnection inputConnection) {
if (mHasUncommittedTypedChars) {
mHasUncommittedTypedChars = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
addToAutoAndUserBigramDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
public boolean getCurrentAutoCapsState() {
InputConnection ic = getCurrentInputConnection();
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCap && ic != null && ei != null && ei.inputType != InputType.TYPE_NULL) {
return ic.getCursorCapsMode(ei.inputType) != 0;
}
return false;
}
private void swapSwapperAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
// It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called.
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == Keyboard.CODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
}
}
private void maybeDoubleSpace() {
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == Keyboard.CODE_SPACE
&& lastThree.charAt(2) == Keyboard.CODE_SPACE
&& mHandler.isAcceptingDoubleSpaces()) {
mHandler.cancelDoubleSpacesTimer();
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
} else {
mHandler.startDoubleSpacesTimer();
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_PERIOD
&& text.charAt(0) == Keyboard.CODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == Keyboard.CODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word to the
// user dictionary
mHandler.postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void onSettingsKeyPressed() {
if (!isShowingOptionDialog()) {
if (!mConfigEnableShowSubtypeSettings) {
showSubtypeSelectorAndSettings();
} else if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
showOptionsMenu();
} else {
launchSettings();
}
}
}
private void onSettingsKeyLongPressed() {
if (!isShowingOptionDialog()) {
if (Utils.hasMultipleEnabledIMEsOrSubtypes(mImm)) {
mImm.showInputMethodPicker();
} else {
launchSettings();
}
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
// Implementation of {@link KeyboardActionListener}.
@Override
public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
KeyboardSwitcher switcher = mKeyboardSwitcher;
final boolean accessibilityEnabled = switcher.isAccessibilityEnabled();
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.CODE_DELETE:
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.CODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch || accessibilityEnabled)
switcher.toggleShift();
break;
case Keyboard.CODE_SWITCH_ALPHA_SYMBOL:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch || accessibilityEnabled)
switcher.changeKeyboardMode();
break;
case Keyboard.CODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case Keyboard.CODE_SETTINGS:
onSettingsKeyPressed();
break;
case Keyboard.CODE_SETTINGS_LONGPRESS:
onSettingsKeyLongPressed();
break;
case LatinKeyboard.CODE_NEXT_LANGUAGE:
toggleLanguage(true);
break;
case LatinKeyboard.CODE_PREV_LANGUAGE:
toggleLanguage(false);
break;
case Keyboard.CODE_CAPSLOCK:
switcher.toggleCapsLock();
break;
case Keyboard.CODE_SHORTCUT:
mSubtypeSwitcher.switchToShortcutIME();
break;
case Keyboard.CODE_TAB:
handleTab();
break;
default:
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode, x, y);
} else {
handleCharacter(primaryCode, keyCodes, x, y);
}
}
switcher.onKey(primaryCode);
// Reset after any single keystroke
mEnteredText = null;
}
@Override
public void onTextInput(CharSequence text) {
mVoiceProxy.commitVoiceInput();
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
mRecorrection.abortRecorrection(false);
ic.beginBatchEdit();
commitTyped(ic);
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
mKeyboardSwitcher.updateShiftState();
mKeyboardSwitcher.onKey(Keyboard.CODE_DUMMY);
mJustAddedMagicSpace = false;
mEnteredText = text;
}
@Override
public void onCancelInput() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace() {
if (mVoiceProxy.logAndRevertVoiceInput()) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
mVoiceProxy.handleBackspace();
boolean deleteChar = false;
if (mHasUncommittedTypedChars) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mHasUncommittedTypedChars = false;
}
if (1 == length) {
// 1 == length means we are about to erase the last character of the word,
// so we can show bigrams.
mHandler.postUpdateBigramPredictions();
} else {
// length > 1, so we still have letters to deduce a suggestion from.
mHandler.postUpdateSuggestions();
}
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
mHandler.postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.isUndoCommit()) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
}
if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Touch again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
ic.endBatchEdit();
}
private void handleTab() {
final int imeOptions = getCurrentInputEditorInfo().imeOptions;
if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
&& !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
return;
}
final InputConnection ic = getCurrentInputConnection();
if (ic == null)
return;
// True if keyboard is in either chording shift or manual temporary upper case mode.
final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase();
if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions)
&& !isManualTemporaryUpperCase) {
EditorInfoCompatUtils.performEditorActionNext(ic);
ic.performEditorAction(EditorInfo.IME_ACTION_NEXT);
} else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)
&& isManualTemporaryUpperCase) {
EditorInfoCompatUtils.performEditorActionPrevious(ic);
}
}
private void handleCharacter(int primaryCode, int[] keyCodes, int x, int y) {
mVoiceProxy.handleCharacter();
if (mJustAddedMagicSpace && isMagicSpaceStripper(primaryCode)) {
removeTrailingSpace();
}
if (mLastSelectionStart == mLastSelectionEnd) {
mRecorrection.abortRecorrection(false);
}
int code = primaryCode;
if (isAlphabet(code) && isSuggestionsRequested() && !isCursorTouchingWord()) {
if (!mHasUncommittedTypedChars) {
mHasUncommittedTypedChars = true;
mComposing.setLength(0);
mRecorrection.saveWordInHistory(mWord, mBestWord);
mWord.reset();
clearSuggestions();
}
}
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (switcher.isShiftedOrShiftLocked()) {
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
code = keyCodes[0];
if (switcher.isAlphabetMode() && Character.isLowerCase(code)) {
int upperCaseCode = Character.toUpperCase(code);
if (upperCaseCode != code) {
code = upperCaseCode;
} else {
// Some keys, such as [eszett], have upper case as multi-characters.
String upperCase = new String(new int[] {code}, 0, 1).toUpperCase();
onTextInput(upperCase);
return;
}
}
}
if (mHasUncommittedTypedChars) {
if (mComposing.length() == 0 && switcher.isAlphabetMode()
&& switcher.isShiftedOrShiftLocked()) {
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) code);
mWord.add(code, keyCodes, x, y);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(getCurrentAutoCapsState());
}
ic.setComposingText(mComposing, 1);
}
mHandler.postUpdateSuggestions();
} else {
sendKeyChar((char)code);
}
if (mJustAddedMagicSpace && isMagicSpaceSwapper(primaryCode)) {
swapSwapperAndSpace();
} else {
mJustAddedMagicSpace = false;
}
switcher.updateShiftState();
if (LatinIME.PERF_DEBUG) measureCps();
TextEntryState.typedCharacter((char) code, isWordSeparator(code), x, y);
}
private void handleSeparator(int primaryCode, int x, int y) {
mVoiceProxy.handleSeparator();
// Should dismiss the "Touch again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
final InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
mRecorrection.abortRecorrection(false);
}
if (mHasUncommittedTypedChars) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
if (mAutoCorrectOn && primaryCode != Keyboard.CODE_SINGLE_QUOTE) {
pickedDefault = pickDefaultSuggestion(primaryCode);
} else {
commitTyped(ic);
}
}
if (mJustAddedMagicSpace) {
if (isMagicSpaceSwapper(primaryCode)) {
sendKeyChar((char)primaryCode);
swapSwapperAndSpace();
} else {
if (isMagicSpaceStripper(primaryCode)) removeTrailingSpace();
sendKeyChar((char)primaryCode);
mJustAddedMagicSpace = false;
}
} else {
sendKeyChar((char)primaryCode);
}
if (isSuggestionsRequested() && primaryCode == Keyboard.CODE_SPACE) {
maybeDoubleSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true, x, y);
if (pickedDefault) {
CharSequence typedWord = mWord.getTypedWord();
TextEntryState.backToAcceptedDefault(typedWord);
if (!TextUtils.isEmpty(typedWord) && !typedWord.equals(mBestWord)) {
InputConnectionCompatUtils.commitCorrection(
ic, mLastSelectionEnd - typedWord.length(), typedWord, mBestWord);
if (mCandidateView != null)
mCandidateView.onAutoCorrectionInverted(mBestWord);
}
}
if (Keyboard.CODE_SPACE == primaryCode) {
if (!isCursorTouchingWord()) {
mHandler.cancelUpdateSuggestions();
mHandler.cancelUpdateOldSuggestions();
mHandler.postUpdateBigramPredictions();
}
} else {
// Set punctuation right away. onUpdateSelection will fire but tests whether it is
// already displayed or not, so it's okay.
setPunctuationSuggestions();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
mVoiceProxy.handleClose();
requestHideSelf(0);
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null)
inputView.closing();
}
public boolean isSuggestionsRequested() {
return mIsSettingsSuggestionStripOn
&& (mCorrectionMode > 0 || isShowingSuggestionsStrip());
}
public boolean isShowingPunctuationList() {
return mSuggestPuncList == mCandidateView.getSuggestions();
}
public boolean isShowingSuggestionsStrip() {
return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE)
|| (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE
&& mOrientation == Configuration.ORIENTATION_PORTRAIT);
}
public boolean isCandidateStripVisible() {
if (mCandidateView == null)
return false;
if (mCandidateView.isShowingAddToDictionaryHint() || TextEntryState.isRecorrecting())
return true;
if (!isShowingSuggestionsStrip())
return false;
if (mApplicationSpecifiedCompletionOn)
return true;
return isSuggestionsRequested();
}
public void switchToKeyboardView() {
if (DEBUG) {
Log.d(TAG, "Switch to keyboard view.");
}
View v = mKeyboardSwitcher.getInputView();
if (v != null) {
// Confirms that the keyboard view doesn't have parent view.
ViewParent p = v.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup) p).removeView(v);
}
setInputView(v);
}
setCandidatesViewShown(isCandidateStripVisible());
updateInputViewShown();
mHandler.postUpdateSuggestions();
}
public void clearSuggestions() {
setSuggestions(SuggestedWords.EMPTY);
}
public void setSuggestions(SuggestedWords words) {
if (mVoiceProxy.getAndResetIsShowingHint()) {
setCandidatesView(mCandidateViewContainer);
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(words);
if (mCandidateView.isConfigCandidateHighlightFontColorEnabled()) {
mKeyboardSwitcher.onAutoCorrectionStateChanged(
words.hasWordAboveAutoCorrectionScoreThreshold());
}
}
}
public void updateSuggestions() {
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isSuggestionsRequested())
&& !mVoiceProxy.isVoiceInputHighlighted()) {
return;
}
if (!mHasUncommittedTypedChars) {
setPunctuationSuggestions();
return;
}
showSuggestions(mWord);
}
private void showSuggestions(WordComposer word) {
// TODO: May need a better way of retrieving previous word
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
mWordSeparators);
SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
mKeyboardSwitcher.getInputView(), word, prevWord);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection();
final CharSequence typedWord = word.getTypedWord();
// Here, we want to promote a whitelisted word if exists.
final boolean typedWordValid = AutoCorrection.isValidWordForAutoCorrection(
mSuggest.getUnigramDictionaries(), typedWord, preferCapitalization());
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isRecorrecting();
// Basically, we update the suggestion strip only when suggestion count > 1. However,
// there is an exception: We update the suggestion strip whenever typed word's length
// is 1 or typed word is found in dictionary, regardless of suggestion count. Actually,
// in most cases, suggestion count is 1 when typed word's length is 1, but we do always
// need to clear the previous state when the user starts typing a word (i.e. typed word's
// length == 1).
if (builder.size() > 1 || typedWord.length() == 1 || typedWordValid
|| mCandidateView.isShowingAddToDictionaryHint()) {
builder.setTypedWordValid(typedWordValid).setHasMinimalSuggestion(correctionAvailable);
} else {
final SuggestedWords previousSuggestions = mCandidateView.getSuggestions();
if (previousSuggestions == mSuggestPuncList)
return;
builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions);
}
showSuggestions(builder.build(), typedWord);
}
public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) {
setSuggestions(suggestedWords);
if (suggestedWords.size() > 0) {
if (Utils.shouldBlockedBySafetyNetForAutoCorrection(suggestedWords, mSuggest)) {
mBestWord = typedWord;
} else if (suggestedWords.hasAutoCorrectionWord()) {
mBestWord = suggestedWords.getWord(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible());
}
private boolean pickDefaultSuggestion(int separatorCode) {
// Complete any pending candidate query first
if (mHandler.hasPendingUpdateSuggestions()) {
mHandler.cancelUpdateSuggestions();
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord, separatorCode);
mJustAccepted = true;
pickSuggestion(mBestWord);
// Add the word to the auto dictionary if it's not a known word
addToAutoAndUserBigramDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0);
+ final boolean oldMagicSpace = mJustAddedMagicSpace;
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
- mJustAddedMagicSpace = false;
+ mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// From there on onUpdateSelection() will fire so suggestions will be updated
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
* @param suggestion the suggestion picked by the user to be committed to
* the text field
*/
private void pickSuggestion(CharSequence suggestion) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
if (!switcher.isKeyboardAvailable())
return;
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
mVoiceProxy.rememberReplacedWord(suggestion, mWordSeparators);
ic.commitText(suggestion, 1);
}
mRecorrection.saveWordInHistory(mWord, suggestion);
mHasUncommittedTypedChars = false;
mCommittedLength = suggestion.length();
}
private static final WordComposer sEmptyWordComposer = new WordComposer();
private void updateBigramPredictions() {
if (mSuggest == null || !isSuggestionsRequested())
return;
if (!mBigramPredictionEnabled) {
setPunctuationSuggestions();
return;
}
final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(),
mWordSeparators);
SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(
mKeyboardSwitcher.getInputView(), sEmptyWordComposer, prevWord);
if (builder.size() > 0) {
// Explicitly supply an empty typed word (the no-second-arg version of
// showSuggestions will retrieve the word near the cursor, we don't want that here)
showSuggestions(builder.build(), "");
} else {
if (!isShowingPunctuationList()) setPunctuationSuggestions();
}
}
public void setPunctuationSuggestions() {
setSuggestions(mSuggestPuncList);
setCandidatesViewShown(isCandidateStripVisible());
}
private void addToAutoAndUserBigramDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToOnlyBigramDictionary(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
* @param selectedANotTypedWord true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta,
boolean selectedANotTypedWord) {
if (suggestion == null || suggestion.length() < 1) return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
final boolean selectedATypedWordAndItsInAutoDic =
!selectedANotTypedWord && mAutoDictionary.isValidWord(suggestion);
final boolean isValidWord = AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true);
final boolean needsToAddToAutoDictionary = selectedATypedWordAndItsInAutoDic
|| !isValidWord;
if (needsToAddToAutoDictionary) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
// We don't want to register as bigrams words separated by a separator.
// For example "I will, and you too" : we don't want the pair ("will" "and") to be
// a bigram.
CharSequence prevWord = EditingUtils.getPreviousWord(getCurrentInputConnection(),
mWordSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
public boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !isWordSeparator(toLeft.charAt(0))
&& !isSuggestedPunctuation(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !isWordSeparator(toRight.charAt(0))
&& !isSuggestedPunctuation(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mHasUncommittedTypedChars && length > 0) {
final InputConnection ic = getCurrentInputConnection();
final CharSequence punctuation = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
final CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (!TextUtils.isEmpty(toTheLeft) && isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
// Re-insert punctuation only when the deleted character was word separator and the
// composing text wasn't equal to the auto-corrected text.
if (deleteChar
&& !TextUtils.isEmpty(punctuation) && isWordSeparator(punctuation.charAt(0))
&& !TextUtils.equals(mComposing, toTheLeft)) {
ic.commitText(mComposing, 1);
TextEntryState.acceptedTyped(mComposing);
ic.commitText(punctuation, 1);
TextEntryState.typedCharacter(punctuation.charAt(0), true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// Clear composing text
mComposing.setLength(0);
} else {
mHasUncommittedTypedChars = true;
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
}
mHandler.cancelUpdateBigramPredictions();
mHandler.postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private boolean isMagicSpaceStripper(int code) {
return mMagicSpaceStrippers.contains(String.valueOf((char)code));
}
private boolean isMagicSpaceSwapper(int code) {
return mMagicSpaceSwappers.contains(String.valueOf((char)code));
}
private void sendMagicSpace() {
sendKeyChar((char)Keyboard.CODE_SPACE);
mJustAddedMagicSpace = true;
mKeyboardSwitcher.updateShiftState();
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
// Notify that language or mode have been changed and toggleLanguage will update KeyboardID
// according to new language or mode.
public void onRefreshKeyboard() {
// Reload keyboard because the current language has been changed.
mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(),
mSubtypeSwitcher.isShortcutImeEnabled() && mVoiceProxy.isVoiceButtonEnabled(),
mVoiceProxy.isVoiceButtonOnPrimary());
initSuggest();
mKeyboardSwitcher.updateShiftState();
}
// "reset" and "next" are used only for USE_SPACEBAR_LANGUAGE_SWITCHER.
private void toggleLanguage(boolean next) {
if (mSubtypeSwitcher.useSpacebarLanguageSwitcher()) {
mSubtypeSwitcher.toggleLanguage(next);
}
onRefreshKeyboard();// no need??
}
@Override
public void onSwipeDown() {
if (mConfigSwipeDownDismissKeyboardEnabled)
handleClose();
}
@Override
public void onPress(int primaryCode, boolean withSliding) {
if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) {
vibrate();
playKeyClick(primaryCode);
}
KeyboardSwitcher switcher = mKeyboardSwitcher;
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) {
switcher.onPressShift(withSliding);
} else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
switcher.onPressSymbol();
} else {
switcher.onOtherKeyPressed();
}
mAccessibilityUtils.onPress(primaryCode, switcher);
}
@Override
public void onRelease(int primaryCode, boolean withSliding) {
KeyboardSwitcher switcher = mKeyboardSwitcher;
// Reset any drag flags in the keyboard
final boolean distinctMultiTouch = switcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.CODE_SHIFT) {
switcher.onReleaseShift(withSliding);
} else if (distinctMultiTouch && primaryCode == Keyboard.CODE_SWITCH_ALPHA_SYMBOL) {
switcher.onReleaseSymbol();
}
mAccessibilityUtils.onRelease(primaryCode, switcher);
}
// receive ringer mode change and network state change.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
updateRingerMode();
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mSubtypeSwitcher.onNetworkStateChanged(intent);
}
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.CODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case Keyboard.CODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case Keyboard.CODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
public void vibrate() {
if (!mVibrateOn) {
return;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
public void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
public WordComposer getCurrentWord() {
return mWord;
}
public boolean getPopupOn() {
return mPopupOn;
}
private void updateCorrectionMode() {
// TODO: cleanup messy flags
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled() {
if (mSuggest == null) return;
mSuggest.setQuickFixesEnabled(mQuickFixes
&& SubtypeSwitcher.getInstance().isSystemLanguageSameAsInputLanguage());
}
private void updateSuggestionVisibility(SharedPreferences prefs) {
final Resources res = mResources;
final String suggestionVisiblityStr = prefs.getString(
Settings.PREF_SHOW_SUGGESTIONS_SETTING,
res.getString(R.string.prefs_suggestion_visibility_default_value));
for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) {
if (suggestionVisiblityStr.equals(res.getString(visibility))) {
mSuggestionVisibility = visibility;
break;
}
}
}
protected void launchSettings() {
launchSettings(Settings.class);
}
public void launchDebugSettings() {
launchSettings(DebugSettings.class);
}
protected void launchSettings(Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings(EditorInfo attribute) {
// Get the settings preferences
final SharedPreferences prefs = mPrefs;
final boolean hasVibrator = VibratorCompatWrapper.getInstance(this).hasVibrator();
mVibrateOn = hasVibrator && prefs.getBoolean(Settings.PREF_VIBRATE_ON, false);
mSoundOn = prefs.getBoolean(Settings.PREF_SOUND_ON,
mResources.getBoolean(R.bool.config_default_sound_enabled));
mPopupOn = isPopupEnabled(prefs);
mAutoCap = prefs.getBoolean(Settings.PREF_AUTO_CAP, true);
mQuickFixes = isQuickFixesEnabled(prefs);
mAutoCorrectEnabled = isAutoCorrectEnabled(prefs);
mBigramSuggestionEnabled = mAutoCorrectEnabled && isBigramSuggestionEnabled(prefs);
mBigramPredictionEnabled = mBigramSuggestionEnabled && isBigramPredictionEnabled(prefs);
loadAndSetAutoCorrectionThreshold(prefs);
mVoiceProxy.loadSettings(attribute, prefs);
updateCorrectionMode();
updateAutoTextEnabled();
updateSuggestionVisibility(prefs);
// This will work only when the subtype is not supported.
LanguageSwitcherProxy.loadSettings();
}
/**
* Load Auto correction threshold from SharedPreferences, and modify mSuggest's threshold.
*/
private void loadAndSetAutoCorrectionThreshold(SharedPreferences sp) {
// When mSuggest is not initialized, cannnot modify mSuggest's threshold.
if (mSuggest == null) return;
// When auto correction setting is turned off, the threshold is ignored.
if (!isAutoCorrectEnabled(sp)) return;
final String currentAutoCorrectionSetting = sp.getString(
Settings.PREF_AUTO_CORRECTION_THRESHOLD,
mResources.getString(R.string.auto_correction_threshold_mode_index_modest));
final String[] autoCorrectionThresholdValues = mResources.getStringArray(
R.array.auto_correction_threshold_values);
// When autoCrrectionThreshold is greater than 1.0, auto correction is virtually turned off.
double autoCorrectionThreshold = Double.MAX_VALUE;
try {
final int arrayIndex = Integer.valueOf(currentAutoCorrectionSetting);
if (arrayIndex >= 0 && arrayIndex < autoCorrectionThresholdValues.length) {
autoCorrectionThreshold = Double.parseDouble(
autoCorrectionThresholdValues[arrayIndex]);
}
} catch (NumberFormatException e) {
// Whenever the threshold settings are correct, never come here.
autoCorrectionThreshold = Double.MAX_VALUE;
Log.w(TAG, "Cannot load auto correction threshold setting."
+ " currentAutoCorrectionSetting: " + currentAutoCorrectionSetting
+ ", autoCorrectionThresholdValues: "
+ Arrays.toString(autoCorrectionThresholdValues));
}
// TODO: This should be refactored :
// setAutoCorrectionThreshold should be called outside of this method.
mSuggest.setAutoCorrectionThreshold(autoCorrectionThreshold);
}
private boolean isPopupEnabled(SharedPreferences sp) {
final boolean showPopupOption = getResources().getBoolean(
R.bool.config_enable_show_popup_on_keypress_option);
if (!showPopupOption) return mResources.getBoolean(R.bool.config_default_popup_preview);
return sp.getBoolean(Settings.PREF_POPUP_ON,
mResources.getBoolean(R.bool.config_default_popup_preview));
}
private boolean isQuickFixesEnabled(SharedPreferences sp) {
final boolean showQuickFixesOption = mResources.getBoolean(
R.bool.config_enable_quick_fixes_option);
if (!showQuickFixesOption) {
return isAutoCorrectEnabled(sp);
}
return sp.getBoolean(Settings.PREF_QUICK_FIXES, mResources.getBoolean(
R.bool.config_default_quick_fixes));
}
private boolean isAutoCorrectEnabled(SharedPreferences sp) {
final String currentAutoCorrectionSetting = sp.getString(
Settings.PREF_AUTO_CORRECTION_THRESHOLD,
mResources.getString(R.string.auto_correction_threshold_mode_index_modest));
final String autoCorrectionOff = mResources.getString(
R.string.auto_correction_threshold_mode_index_off);
return !currentAutoCorrectionSetting.equals(autoCorrectionOff);
}
private boolean isBigramSuggestionEnabled(SharedPreferences sp) {
final boolean showBigramSuggestionsOption = mResources.getBoolean(
R.bool.config_enable_bigram_suggestions_option);
if (!showBigramSuggestionsOption) {
return isAutoCorrectEnabled(sp);
}
return sp.getBoolean(Settings.PREF_BIGRAM_SUGGESTIONS, mResources.getBoolean(
R.bool.config_default_bigram_suggestions));
}
private boolean isBigramPredictionEnabled(SharedPreferences sp) {
return sp.getBoolean(Settings.PREF_BIGRAM_PREDICTIONS, mResources.getBoolean(
R.bool.config_default_bigram_prediction));
}
private void initSuggestPuncList() {
if (mSuggestPuncs != null || mSuggestPuncList != null)
return;
SuggestedWords.Builder builder = new SuggestedWords.Builder();
String puncs = mResources.getString(R.string.suggested_punctuations);
if (puncs != null) {
for (int i = 0; i < puncs.length(); i++) {
builder.addWord(puncs.subSequence(i, i + 1));
}
}
mSuggestPuncList = builder.build();
mSuggestPuncs = puncs;
}
private boolean isSuggestedPunctuation(int code) {
return mSuggestPuncs.contains(String.valueOf((char)code));
}
private void showSubtypeSelectorAndSettings() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
// TODO: Should use new string "Select active input modes".
getString(R.string.language_selection_title),
getString(R.string.english_ime_settings),
};
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
Intent intent = CompatUtils.getInputLanguageSelectionIntent(
mInputMethodId, Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case 1:
launchSettings();
break;
}
}
};
showOptionsMenuInternal(title, items, listener);
}
private void showOptionsMenu() {
final CharSequence title = getString(R.string.english_ime_input_options);
final CharSequence[] items = new CharSequence[] {
getString(R.string.selectInputMethod),
getString(R.string.english_ime_settings),
};
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case 0:
mImm.showInputMethodPicker();
break;
case 1:
launchSettings();
break;
}
}
};
showOptionsMenuInternal(title, items, listener);
}
private void showOptionsMenuInternal(CharSequence title, CharSequence[] items,
DialogInterface.OnClickListener listener) {
final IBinder windowToken = mKeyboardSwitcher.getInputView().getWindowToken();
if (windowToken == null) return;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
builder.setItems(items, listener);
builder.setTitle(title);
mOptionsDialog = builder.create();
mOptionsDialog.setCanceledOnTouchOutside(true);
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
@Override
protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mComposing=" + mComposing.toString());
p.println(" mIsSuggestionsRequested=" + mIsSettingsSuggestionStripOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mHasUncommittedTypedChars=" + mHasUncommittedTypedChars);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mShouldInsertMagicSpace=" + mShouldInsertMagicSpace);
p.println(" mApplicationSpecifiedCompletionOn=" + mApplicationSpecifiedCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
p.println(" mPopupOn=" + mPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
}
| false | true | public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0);
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
mJustAddedMagicSpace = false;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// From there on onUpdateSelection() will fire so suggestions will be updated
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
| public void pickSuggestionManually(int index, CharSequence suggestion) {
SuggestedWords suggestions = mCandidateView.getSuggestions();
mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mWordSeparators);
final boolean recorrecting = TextEntryState.isRecorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null
&& index >= 0 && index < mApplicationSpecifiedCompletions.length) {
CompletionInfo ci = mApplicationSpecifiedCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
mKeyboardSwitcher.updateShiftState();
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions.mWords);
// Find out whether the previous character is a space. If it is, as a special case
// for punctuation entered through the suggestion strip, it should be considered
// a magic space even if it was a normal space. This is meant to help in case the user
// pressed space on purpose of displaying the suggestion strip punctuation.
final char primaryCode = suggestion.charAt(0);
final int toLeft = (ic == null) ? 0 : ic.getTextBeforeCursor(1, 0).charAt(0);
final boolean oldMagicSpace = mJustAddedMagicSpace;
if (Keyboard.CODE_SPACE == toLeft) mJustAddedMagicSpace = true;
onCodeInput(primaryCode, new int[] { primaryCode },
KeyboardActionListener.NOT_A_TOUCH_COORDINATE,
KeyboardActionListener.NOT_A_TOUCH_COORDINATE);
mJustAddedMagicSpace = oldMagicSpace;
if (ic != null) {
ic.endBatchEdit();
}
return;
}
if (!mHasUncommittedTypedChars) {
// If we are not composing a word, then it was a suggestion inferred from
// context - no user input. We should reset the word composer.
mWord.reset();
}
mJustAccepted = true;
pickSuggestion(suggestion);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToAutoAndUserBigramDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToOnlyBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions.mWords);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mShouldInsertMagicSpace && !recorrecting) {
sendMagicSpace();
}
// We should show the hint if the user pressed the first entry AND either:
// - There is no dictionary (we know that because we tried to load it => null != mSuggest
// AND mHasDictionary is false)
// - There is a dictionary and the word is not in it
// Please note that if mSuggest is null, it means that everything is off: suggestion
// and correction, so we shouldn't try to show the hint
// We used to look at mCorrectionMode here, but showing the hint should have nothing
// to do with the autocorrection setting.
final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null
// If there is no dictionary the hint should be shown.
&& (!mHasDictionary
// If "suggestion" is not in the dictionary, the hint should be shown.
|| !AutoCorrection.isValidWord(
mSuggest.getUnigramDictionaries(), suggestion, true));
if (!recorrecting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) Keyboard.CODE_SPACE, true,
WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE);
// From there on onUpdateSelection() will fire so suggestions will be updated
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
mHandler.postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/AbstractTcfLaunchTabContainerEditorPage.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/AbstractTcfLaunchTabContainerEditorPage.java
index ada7fd55f..957f5ced8 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/AbstractTcfLaunchTabContainerEditorPage.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.launch.ui/src/org/eclipse/tcf/te/tcf/launch/ui/editor/AbstractTcfLaunchTabContainerEditorPage.java
@@ -1,220 +1,222 @@
/*******************************************************************************
* Copyright (c) 2012 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.launch.ui.editor;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationListener;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage;
import org.eclipse.tcf.te.runtime.concurrent.util.ExecutorsUtil;
import org.eclipse.tcf.te.runtime.persistence.PersistenceManager;
import org.eclipse.tcf.te.runtime.persistence.interfaces.IPersistenceDelegate;
import org.eclipse.tcf.te.runtime.services.ServiceManager;
import org.eclipse.tcf.te.runtime.services.interfaces.IPropertiesAccessService;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel;
/**
* TCF launch configuration tab container page implementation.
*/
public abstract class AbstractTcfLaunchTabContainerEditorPage extends AbstractLaunchTabContainerEditorPage implements ILaunchConfigurationListener {
protected ILaunchConfigurationListener launchConfigListener = null;
protected static final String PROP_LAUNCH_CONFIG_WC = "launchConfigWorkingCopy.transient.silent"; //$NON-NLS-1$
protected static final String PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES = "launchConfigAttributes.transient.silent"; //$NON-NLS-1$
/**
* Get the peer model from the editor input.
* @param input The editor input.
* @return The peer model.
*/
public IPeerModel getPeerModel(Object input) {
return (IPeerModel)((IAdaptable)input).getAdapter(IPeerModel.class);
}
/**
* Get the launch configuration from the peer model.
* @param peerModel The peer model.
* @return The launch configuration.
*/
public ILaunchConfigurationWorkingCopy getLaunchConfig(final IPeerModel peerModel) {
ILaunchConfigurationWorkingCopy wc = null;
if (peerModel != null) {
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
Assert.isNotNull(service);
if (service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC) instanceof ILaunchConfigurationWorkingCopy) {
wc = (ILaunchConfigurationWorkingCopy)service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC);
}
else {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().getAdapter(peerModel, ILaunchConfigurationWorkingCopy.class);
if (wc == null) {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().loadAdapter(peerModel, "org.eclipse.debug.core.ILaunchConfigurationWorkingCopy"); //$NON-NLS-1$
}
+ Assert.isNotNull(wc);
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, wc);
IPersistenceDelegate delegate = PersistenceManager.getInstance().getDelegate(wc, String.class);
String launchConfigAttributes = null;
try {
- launchConfigAttributes = (String)delegate.write(wc, String.class);
+ launchConfigAttributes = delegate != null ? (String)delegate.write(wc, String.class) : null;
}
catch (Exception e) {
+ /* ignored on purpose */
}
service.setProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES, launchConfigAttributes);
}
}
return wc;
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage#setupData(java.lang.Object)
*/
@Override
public boolean setupData(Object input) {
ILaunchConfigurationWorkingCopy wc = getLaunchConfig(getPeerModel(input));
if (wc != null) {
getLaunchConfigurationTab().initializeFrom(wc);
checkLaunchConfigDirty();
return true;
}
return false;
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage#extractData()
*/
@Override
public boolean extractData() {
ILaunchConfigurationWorkingCopy wc = getLaunchConfig(getPeerModel(getEditorInput()));
if (wc != null && checkLaunchConfigDirty()) {
getLaunchConfigurationTab().performApply(wc);
try {
wc.doSave();
IPeerModel peerModel = getPeerModel(getEditorInput());
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
Assert.isNotNull(service);
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, null);
checkLaunchConfigDirty();
return true;
}
catch (Exception e) {
}
}
return false;
}
/**
* Check if the launch configuration has changed.
* If it has changed, the page is set dirty.
* @return <code>true</code> if the launch configuration has changed since last save.
*/
public boolean checkLaunchConfigDirty() {
boolean dirty = false;
IPeerModel peerModel = getPeerModel(getEditorInput());
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
String oldLaunchConfigAttributes = (String)service.getProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES);
IPersistenceDelegate delegate = PersistenceManager.getInstance().getDelegate(getLaunchConfig(peerModel), String.class);
String launchConfigAttributes = null;
try {
launchConfigAttributes = (String)delegate.write(getLaunchConfig(peerModel), String.class);
dirty = !launchConfigAttributes.equals(oldLaunchConfigAttributes);
}
catch (Exception e) {
}
setDirty(dirty);
return dirty;
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage#setDirty(boolean)
*/
@Override
public void setDirty(boolean dirty) {
super.setDirty(dirty);
ExecutorsUtil.executeInUI(new Runnable() {
@Override
public void run() {
getManagedForm().dirtyStateChanged();
}
});
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage#setActive(boolean)
*/
@Override
public void setActive(boolean active) {
super.setActive(active);
if (active && launchConfigListener == null) {
launchConfigListener = this;
DebugPlugin.getDefault().getLaunchManager().addLaunchConfigurationListener(this);
}
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.launch.ui.editor.AbstractLaunchTabContainerEditorPage#dispose()
*/
@Override
public void dispose() {
super.dispose();
IPeerModel peerModel = getPeerModel(getEditorInput());
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
service.setProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES, null);
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, null);
DebugPlugin.getDefault().getLaunchManager().removeLaunchConfigurationListener(this);
launchConfigListener = null;
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.ILaunchConfigurationListener#launchConfigurationAdded(org.eclipse.debug.core.ILaunchConfiguration)
*/
@Override
public void launchConfigurationAdded(ILaunchConfiguration configuration) {
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.ILaunchConfigurationListener#launchConfigurationRemoved(org.eclipse.debug.core.ILaunchConfiguration)
*/
@Override
public void launchConfigurationRemoved(ILaunchConfiguration configuration) {
}
/* (non-Javadoc)
* @see org.eclipse.debug.core.ILaunchConfigurationListener#launchConfigurationChanged(org.eclipse.debug.core.ILaunchConfiguration)
*/
@Override
public void launchConfigurationChanged(ILaunchConfiguration configuration) {
if (!(configuration instanceof ILaunchConfigurationWorkingCopy)) {
IPeerModel peerModel = getPeerModel(getEditorInput());
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
ILaunchConfigurationWorkingCopy wc = (ILaunchConfigurationWorkingCopy)service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC);
if (wc != null && configuration.getName().equals(wc.getName())) {
service.setProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES, null);
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, null);
ExecutorsUtil.executeInUI(new Runnable() {
@Override
public void run() {
setActive(isActive());
}
});
}
}
}
/* (non-Javadoc)
* @see org.eclipse.tcf.te.ui.views.editor.pages.AbstractEditorPage#doValidate()
*/
@Override
protected ValidationResult doValidate() {
return null;
}
}
| false | true | public ILaunchConfigurationWorkingCopy getLaunchConfig(final IPeerModel peerModel) {
ILaunchConfigurationWorkingCopy wc = null;
if (peerModel != null) {
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
Assert.isNotNull(service);
if (service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC) instanceof ILaunchConfigurationWorkingCopy) {
wc = (ILaunchConfigurationWorkingCopy)service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC);
}
else {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().getAdapter(peerModel, ILaunchConfigurationWorkingCopy.class);
if (wc == null) {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().loadAdapter(peerModel, "org.eclipse.debug.core.ILaunchConfigurationWorkingCopy"); //$NON-NLS-1$
}
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, wc);
IPersistenceDelegate delegate = PersistenceManager.getInstance().getDelegate(wc, String.class);
String launchConfigAttributes = null;
try {
launchConfigAttributes = (String)delegate.write(wc, String.class);
}
catch (Exception e) {
}
service.setProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES, launchConfigAttributes);
}
}
return wc;
}
| public ILaunchConfigurationWorkingCopy getLaunchConfig(final IPeerModel peerModel) {
ILaunchConfigurationWorkingCopy wc = null;
if (peerModel != null) {
IPropertiesAccessService service = ServiceManager.getInstance().getService(peerModel, IPropertiesAccessService.class);
Assert.isNotNull(service);
if (service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC) instanceof ILaunchConfigurationWorkingCopy) {
wc = (ILaunchConfigurationWorkingCopy)service.getProperty(peerModel, PROP_LAUNCH_CONFIG_WC);
}
else {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().getAdapter(peerModel, ILaunchConfigurationWorkingCopy.class);
if (wc == null) {
wc = (ILaunchConfigurationWorkingCopy)Platform.getAdapterManager().loadAdapter(peerModel, "org.eclipse.debug.core.ILaunchConfigurationWorkingCopy"); //$NON-NLS-1$
}
Assert.isNotNull(wc);
service.setProperty(peerModel, PROP_LAUNCH_CONFIG_WC, wc);
IPersistenceDelegate delegate = PersistenceManager.getInstance().getDelegate(wc, String.class);
String launchConfigAttributes = null;
try {
launchConfigAttributes = delegate != null ? (String)delegate.write(wc, String.class) : null;
}
catch (Exception e) {
/* ignored on purpose */
}
service.setProperty(peerModel, PROP_ORIGINAL_LAUNCH_CONFIG_ATTRIBUTES, launchConfigAttributes);
}
}
return wc;
}
|
diff --git a/plugins-dev/echosounder/pt/lsts/neptus/plugins/echosounder/EchoSounderMRARuler.java b/plugins-dev/echosounder/pt/lsts/neptus/plugins/echosounder/EchoSounderMRARuler.java
index b9bad90b0..6bb394649 100644
--- a/plugins-dev/echosounder/pt/lsts/neptus/plugins/echosounder/EchoSounderMRARuler.java
+++ b/plugins-dev/echosounder/pt/lsts/neptus/plugins/echosounder/EchoSounderMRARuler.java
@@ -1,108 +1,107 @@
/*
* Copyright (c) 2004-2014 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENSE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author: hfq
* Feb 18, 2014
*/
package pt.lsts.neptus.plugins.echosounder;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JLabel;
/**
* @author hfq
*
*/
public class EchoSounderMRARuler extends JLabel {
private static final long serialVersionUID = 1L;
private EchoSounderMRA echoSounderMRA;
public final static int RULER_WIDTH = 20;
protected int maxValue;
protected int minValue;
private int rulerHeight;
/**
* @param echoSounderMRA
*/
public EchoSounderMRARuler(EchoSounderMRA echoSounderMRA) {
super();
this.echoSounderMRA = echoSounderMRA;
this.maxValue = echoSounderMRA.maxRange;
this.minValue = echoSounderMRA.minRange;
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
rulerHeight = echoSounderMRA.getHeight() - 1;
Rectangle drawRulerHere = new Rectangle(0, 0, RULER_WIDTH, rulerHeight);
g2d.setColor(Color.LIGHT_GRAY);
g2d.fill(drawRulerHere);
// Do the ruler labels in a small font that's black.
g2d.setFont(new Font("SansSerif", Font.PLAIN, 8));
g2d.setColor(Color.BLACK);
g2d.drawLine(0, 0, 0, rulerHeight);
g2d.drawLine(RULER_WIDTH, 0, RULER_WIDTH, rulerHeight);
double stepRuler = (double) rulerHeight / (double) (maxValue - minValue);
int i = 0;
- for(double step = 0; step <= rulerHeight; step += stepRuler) {
+ for(double step = 0; i <= maxValue; step += stepRuler, ++i) {
if ((i % 10) == 0) {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 3), (int) step, RULER_WIDTH, (int) step);
if (i == minValue)
g2d.drawString("" + i, 5, (int) step + 7);
else if (i == maxValue)
g2d.drawString("" + i, 1, (int) step - 1);
else
g2d.drawString("" + i, 1, (int) step + 3);
}
else if ((i % 5) == 0){
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 4), (int) step, RULER_WIDTH, (int) step);
}
else {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 6), (int) step, RULER_WIDTH, (int) step);
}
- ++i;
}
}
}
| false | true | protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
rulerHeight = echoSounderMRA.getHeight() - 1;
Rectangle drawRulerHere = new Rectangle(0, 0, RULER_WIDTH, rulerHeight);
g2d.setColor(Color.LIGHT_GRAY);
g2d.fill(drawRulerHere);
// Do the ruler labels in a small font that's black.
g2d.setFont(new Font("SansSerif", Font.PLAIN, 8));
g2d.setColor(Color.BLACK);
g2d.drawLine(0, 0, 0, rulerHeight);
g2d.drawLine(RULER_WIDTH, 0, RULER_WIDTH, rulerHeight);
double stepRuler = (double) rulerHeight / (double) (maxValue - minValue);
int i = 0;
for(double step = 0; step <= rulerHeight; step += stepRuler) {
if ((i % 10) == 0) {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 3), (int) step, RULER_WIDTH, (int) step);
if (i == minValue)
g2d.drawString("" + i, 5, (int) step + 7);
else if (i == maxValue)
g2d.drawString("" + i, 1, (int) step - 1);
else
g2d.drawString("" + i, 1, (int) step + 3);
}
else if ((i % 5) == 0){
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 4), (int) step, RULER_WIDTH, (int) step);
}
else {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 6), (int) step, RULER_WIDTH, (int) step);
}
++i;
}
}
| protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
rulerHeight = echoSounderMRA.getHeight() - 1;
Rectangle drawRulerHere = new Rectangle(0, 0, RULER_WIDTH, rulerHeight);
g2d.setColor(Color.LIGHT_GRAY);
g2d.fill(drawRulerHere);
// Do the ruler labels in a small font that's black.
g2d.setFont(new Font("SansSerif", Font.PLAIN, 8));
g2d.setColor(Color.BLACK);
g2d.drawLine(0, 0, 0, rulerHeight);
g2d.drawLine(RULER_WIDTH, 0, RULER_WIDTH, rulerHeight);
double stepRuler = (double) rulerHeight / (double) (maxValue - minValue);
int i = 0;
for(double step = 0; i <= maxValue; step += stepRuler, ++i) {
if ((i % 10) == 0) {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 3), (int) step, RULER_WIDTH, (int) step);
if (i == minValue)
g2d.drawString("" + i, 5, (int) step + 7);
else if (i == maxValue)
g2d.drawString("" + i, 1, (int) step - 1);
else
g2d.drawString("" + i, 1, (int) step + 3);
}
else if ((i % 5) == 0){
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 4), (int) step, RULER_WIDTH, (int) step);
}
else {
g2d.drawLine(RULER_WIDTH - (RULER_WIDTH / 6), (int) step, RULER_WIDTH, (int) step);
}
}
}
|
diff --git a/Arena/src/game/View.java b/Arena/src/game/View.java
index ca08629..357feae 100644
--- a/Arena/src/game/View.java
+++ b/Arena/src/game/View.java
@@ -1,56 +1,56 @@
package game;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Class for the GUI
*
* @author Jacob Charles, Dean Hamlin
*
*/
public class View extends JFrame {
/**
* Standard constructor
*/
public View() {
super();
this.setTitle("TSPArena");
this.getContentPane().setPreferredSize(new Dimension(640, 480));
this.pack(); //FORCE it to be 640 x 480, this has given me grief
this.setVisible(true);
this.setResizable(false);
}
/**
* Connects a controller to the screen
*
* @param c
* the controller object to be connected
*/
public void attachController(Controller c) {
this.addKeyListener(new ControlListener(c));
}
/**
* Draw a game state (double buffered)
*
* @param state
* game state to draw
*/
public void reDraw(ClientGameState state){
this.setTitle("TSPArena: "+state.getMapName());
Image backBuffer = createImage(640, 480);
state.draw(backBuffer.getGraphics());
- //test current dimensions
- backBuffer.getGraphics().drawString(""+this.getContentPane().getWidth(), 20, 100);
- backBuffer.getGraphics().drawString(""+this.getContentPane().getHeight(), 20, 120);
+ //illustrate how wrong the current dimensions are
+ backBuffer.getGraphics().drawString(""+(this.getContentPane().getWidth()-640), 20, 100);
+ backBuffer.getGraphics().drawString(""+(this.getContentPane().getHeight()-480), 20, 120);
this.getContentPane().getGraphics().drawImage(backBuffer, 0, 0, null);
}
}
| true | true | public void reDraw(ClientGameState state){
this.setTitle("TSPArena: "+state.getMapName());
Image backBuffer = createImage(640, 480);
state.draw(backBuffer.getGraphics());
//test current dimensions
backBuffer.getGraphics().drawString(""+this.getContentPane().getWidth(), 20, 100);
backBuffer.getGraphics().drawString(""+this.getContentPane().getHeight(), 20, 120);
this.getContentPane().getGraphics().drawImage(backBuffer, 0, 0, null);
}
| public void reDraw(ClientGameState state){
this.setTitle("TSPArena: "+state.getMapName());
Image backBuffer = createImage(640, 480);
state.draw(backBuffer.getGraphics());
//illustrate how wrong the current dimensions are
backBuffer.getGraphics().drawString(""+(this.getContentPane().getWidth()-640), 20, 100);
backBuffer.getGraphics().drawString(""+(this.getContentPane().getHeight()-480), 20, 120);
this.getContentPane().getGraphics().drawImage(backBuffer, 0, 0, null);
}
|
diff --git a/src/java/org/jivesoftware/spark/ui/conferences/DataFormDialog.java b/src/java/org/jivesoftware/spark/ui/conferences/DataFormDialog.java
index 040bcc8d..35333f3f 100644
--- a/src/java/org/jivesoftware/spark/ui/conferences/DataFormDialog.java
+++ b/src/java/org/jivesoftware/spark/ui/conferences/DataFormDialog.java
@@ -1,286 +1,288 @@
/**
* $RCSfile: ,v $
* $Revision: $
* $Date: $
*
* Copyright (C) 2004-2010 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.spark.ui.conferences;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.jivesoftware.resource.Res;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.spark.component.CheckBoxList;
import org.jivesoftware.spark.util.GraphicUtils;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.log.Log;
public class DataFormDialog extends JPanel {
private static final long serialVersionUID = -1536217028590811636L;
private final Map<String,JComponent> valueMap = new HashMap<String,JComponent>();
private int row = 0;
JDialog dialog = null;
public DataFormDialog(JFrame parent, final MultiUserChat chat, final Form submitForm) {
dialog = new JDialog(parent, true);
dialog.setTitle(Res.getString("title.configure.chat.room"));
this.setLayout(new GridBagLayout());
Form form = null;
// Create the room
try {
form = chat.getConfigurationForm();
}
catch (XMPPException e) {
Log.error(e);
}
// Create a new form to submit based on the original form
try {
Iterator<FormField> fields = form.getFields();
// Add default answers to the form to submit
while (fields.hasNext()) {
FormField field = fields.next();
submitForm.addField(field);
String variable = field.getVariable();
String label = field.getLabel();
String type = field.getType();
Iterator iter = field.getValues();
List<Object> valueList = new ArrayList<Object>();
while (iter.hasNext()) {
valueList.add(iter.next());
}
if (type.equals(FormField.TYPE_BOOLEAN)) {
String o = (String)valueList.get(0);
boolean isSelected = o.equals("1");
JCheckBox box = new JCheckBox(label);
box.setSelected(isSelected);
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_TEXT_SINGLE) ||
type.equals(FormField.TYPE_JID_SINGLE)) {
String value = (String)valueList.get(0);
addField(label, new JTextField(value), variable);
}
else if (type.equals(FormField.TYPE_TEXT_MULTI) ||
type.equals(FormField.TYPE_JID_MULTI)) {
StringBuffer buf = new StringBuffer();
iter = field.getValues();
while (iter.hasNext()) {
buf.append((String)iter.next());
if (iter.hasNext()) {
buf.append(",");
}
}
addField(label, new JTextArea(buf.toString()), variable);
}
else if (type.equals(FormField.TYPE_TEXT_PRIVATE)) {
addField(label, new JPasswordField(), variable);
}
else if (type.equals(FormField.TYPE_LIST_SINGLE)) {
JComboBox box = new JComboBox();
iter = field.getOptions();
while (iter.hasNext()) {
FormField.Option option = (FormField.Option)iter.next();
String value = option.getValue();
box.addItem(value);
}
if (valueList.size() > 0) {
String defaultValue = (String)valueList.get(0);
box.setSelectedItem(defaultValue);
}
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_LIST_MULTI)) {
CheckBoxList checkBoxList = new CheckBoxList();
Iterator i = field.getValues();
while (i.hasNext()) {
String value = (String)i.next();
checkBoxList.addCheckBox(new JCheckBox(value), value);
}
addField(label, checkBoxList, variable);
}
}
}
catch (NullPointerException e) {
Log.error(e);
}
JButton button = new JButton();
ResourceUtils.resButton(button, Res.getString("button.update"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
// Now submit all information
updateRoomConfiguration(submitForm, chat);
}
});
final JScrollPane pane = new JScrollPane(this);
+ pane.getVerticalScrollBar().setBlockIncrement(200);
+ pane.getVerticalScrollBar().setUnitIncrement(20);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(pane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(button);
JButton cancelButton = new JButton();
ResourceUtils.resButton(cancelButton, Res.getString("button.cancel"));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dialog.dispose();
}
});
bottomPanel.add(cancelButton);
dialog.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
dialog.pack();
dialog.setSize(600, 400);
GraphicUtils.centerWindowOnScreen(dialog);
dialog.setVisible(true);
}
private void updateRoomConfiguration(Form submitForm, MultiUserChat chat) {
for (Object o1 : valueMap.keySet()) {
String answer = (String) o1;
Object o = valueMap.get(answer);
if (o instanceof JCheckBox) {
boolean isSelected = ((JCheckBox) o).isSelected();
submitForm.setAnswer(answer, isSelected);
} else if (o instanceof JTextArea) {
List<String> list = new ArrayList<String>();
String value = ((JTextArea) o).getText();
StringTokenizer tokenizer = new StringTokenizer(value, ", ", false);
while (tokenizer.hasMoreTokens()) {
list.add(tokenizer.nextToken());
}
if (list.size() > 0) {
submitForm.setAnswer(answer, list);
}
} else if (o instanceof JTextField) {
String value = ((JTextField) o).getText();
if (ModelUtil.hasLength(value)) {
submitForm.setAnswer(answer, value);
}
} else if (o instanceof JComboBox) {
String value = (String) ((JComboBox) o).getSelectedItem();
List<String> list = new ArrayList<String>();
list.add(value);
if (list.size() > 0) {
submitForm.setAnswer(answer, list);
}
} else if (o instanceof CheckBoxList) {
List list = ((CheckBoxList) o).getSelectedValues();
if (list.size() > 0) {
submitForm.setAnswer(answer, list);
}
}
}
try {
chat.sendConfigurationForm(submitForm);
}
catch (XMPPException e) {
Log.error(e);
}
}
private void addField(String label, JComponent comp, String variable) {
if (!(comp instanceof JCheckBox)) {
JLabel formLabel = new JLabel(label);
formLabel.setFont(new Font("dialog", Font.BOLD, 10));
this.add(formLabel, new GridBagConstraints(0, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
}
if (comp instanceof JTextArea) {
JScrollPane pane = new JScrollPane(comp);
pane.setBorder(BorderFactory.createTitledBorder(Res.getString("group.comma.delimited")));
this.add(pane, new GridBagConstraints(1, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 75, 50));
}
else if (comp instanceof JCheckBox) {
this.add(comp, new GridBagConstraints(0, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
}
else if (comp instanceof CheckBoxList) {
this.add(comp, new GridBagConstraints(1, row, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 75, 50));
}
else {
this.add(comp, new GridBagConstraints(1, row, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 75, 0));
}
valueMap.put(variable, comp);
row++;
}
public String getValue(String label) {
Component comp = valueMap.get(label);
if (comp instanceof JCheckBox) {
return "" + ((JCheckBox)comp).isSelected();
}
if (comp instanceof JTextField) {
return ((JTextField)comp).getText();
}
return null;
}
}
| true | true | public DataFormDialog(JFrame parent, final MultiUserChat chat, final Form submitForm) {
dialog = new JDialog(parent, true);
dialog.setTitle(Res.getString("title.configure.chat.room"));
this.setLayout(new GridBagLayout());
Form form = null;
// Create the room
try {
form = chat.getConfigurationForm();
}
catch (XMPPException e) {
Log.error(e);
}
// Create a new form to submit based on the original form
try {
Iterator<FormField> fields = form.getFields();
// Add default answers to the form to submit
while (fields.hasNext()) {
FormField field = fields.next();
submitForm.addField(field);
String variable = field.getVariable();
String label = field.getLabel();
String type = field.getType();
Iterator iter = field.getValues();
List<Object> valueList = new ArrayList<Object>();
while (iter.hasNext()) {
valueList.add(iter.next());
}
if (type.equals(FormField.TYPE_BOOLEAN)) {
String o = (String)valueList.get(0);
boolean isSelected = o.equals("1");
JCheckBox box = new JCheckBox(label);
box.setSelected(isSelected);
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_TEXT_SINGLE) ||
type.equals(FormField.TYPE_JID_SINGLE)) {
String value = (String)valueList.get(0);
addField(label, new JTextField(value), variable);
}
else if (type.equals(FormField.TYPE_TEXT_MULTI) ||
type.equals(FormField.TYPE_JID_MULTI)) {
StringBuffer buf = new StringBuffer();
iter = field.getValues();
while (iter.hasNext()) {
buf.append((String)iter.next());
if (iter.hasNext()) {
buf.append(",");
}
}
addField(label, new JTextArea(buf.toString()), variable);
}
else if (type.equals(FormField.TYPE_TEXT_PRIVATE)) {
addField(label, new JPasswordField(), variable);
}
else if (type.equals(FormField.TYPE_LIST_SINGLE)) {
JComboBox box = new JComboBox();
iter = field.getOptions();
while (iter.hasNext()) {
FormField.Option option = (FormField.Option)iter.next();
String value = option.getValue();
box.addItem(value);
}
if (valueList.size() > 0) {
String defaultValue = (String)valueList.get(0);
box.setSelectedItem(defaultValue);
}
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_LIST_MULTI)) {
CheckBoxList checkBoxList = new CheckBoxList();
Iterator i = field.getValues();
while (i.hasNext()) {
String value = (String)i.next();
checkBoxList.addCheckBox(new JCheckBox(value), value);
}
addField(label, checkBoxList, variable);
}
}
}
catch (NullPointerException e) {
Log.error(e);
}
JButton button = new JButton();
ResourceUtils.resButton(button, Res.getString("button.update"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
// Now submit all information
updateRoomConfiguration(submitForm, chat);
}
});
final JScrollPane pane = new JScrollPane(this);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(pane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(button);
JButton cancelButton = new JButton();
ResourceUtils.resButton(cancelButton, Res.getString("button.cancel"));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dialog.dispose();
}
});
bottomPanel.add(cancelButton);
dialog.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
dialog.pack();
dialog.setSize(600, 400);
GraphicUtils.centerWindowOnScreen(dialog);
dialog.setVisible(true);
}
| public DataFormDialog(JFrame parent, final MultiUserChat chat, final Form submitForm) {
dialog = new JDialog(parent, true);
dialog.setTitle(Res.getString("title.configure.chat.room"));
this.setLayout(new GridBagLayout());
Form form = null;
// Create the room
try {
form = chat.getConfigurationForm();
}
catch (XMPPException e) {
Log.error(e);
}
// Create a new form to submit based on the original form
try {
Iterator<FormField> fields = form.getFields();
// Add default answers to the form to submit
while (fields.hasNext()) {
FormField field = fields.next();
submitForm.addField(field);
String variable = field.getVariable();
String label = field.getLabel();
String type = field.getType();
Iterator iter = field.getValues();
List<Object> valueList = new ArrayList<Object>();
while (iter.hasNext()) {
valueList.add(iter.next());
}
if (type.equals(FormField.TYPE_BOOLEAN)) {
String o = (String)valueList.get(0);
boolean isSelected = o.equals("1");
JCheckBox box = new JCheckBox(label);
box.setSelected(isSelected);
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_TEXT_SINGLE) ||
type.equals(FormField.TYPE_JID_SINGLE)) {
String value = (String)valueList.get(0);
addField(label, new JTextField(value), variable);
}
else if (type.equals(FormField.TYPE_TEXT_MULTI) ||
type.equals(FormField.TYPE_JID_MULTI)) {
StringBuffer buf = new StringBuffer();
iter = field.getValues();
while (iter.hasNext()) {
buf.append((String)iter.next());
if (iter.hasNext()) {
buf.append(",");
}
}
addField(label, new JTextArea(buf.toString()), variable);
}
else if (type.equals(FormField.TYPE_TEXT_PRIVATE)) {
addField(label, new JPasswordField(), variable);
}
else if (type.equals(FormField.TYPE_LIST_SINGLE)) {
JComboBox box = new JComboBox();
iter = field.getOptions();
while (iter.hasNext()) {
FormField.Option option = (FormField.Option)iter.next();
String value = option.getValue();
box.addItem(value);
}
if (valueList.size() > 0) {
String defaultValue = (String)valueList.get(0);
box.setSelectedItem(defaultValue);
}
addField(label, box, variable);
}
else if (type.equals(FormField.TYPE_LIST_MULTI)) {
CheckBoxList checkBoxList = new CheckBoxList();
Iterator i = field.getValues();
while (i.hasNext()) {
String value = (String)i.next();
checkBoxList.addCheckBox(new JCheckBox(value), value);
}
addField(label, checkBoxList, variable);
}
}
}
catch (NullPointerException e) {
Log.error(e);
}
JButton button = new JButton();
ResourceUtils.resButton(button, Res.getString("button.update"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
// Now submit all information
updateRoomConfiguration(submitForm, chat);
}
});
final JScrollPane pane = new JScrollPane(this);
pane.getVerticalScrollBar().setBlockIncrement(200);
pane.getVerticalScrollBar().setUnitIncrement(20);
dialog.getContentPane().setLayout(new BorderLayout());
dialog.getContentPane().add(pane, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(button);
JButton cancelButton = new JButton();
ResourceUtils.resButton(cancelButton, Res.getString("button.cancel"));
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
dialog.dispose();
}
});
bottomPanel.add(cancelButton);
dialog.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
dialog.pack();
dialog.setSize(600, 400);
GraphicUtils.centerWindowOnScreen(dialog);
dialog.setVisible(true);
}
|
diff --git a/src/GUI/NewOperations.java b/src/GUI/NewOperations.java
index 3a5d41c..0c7b78d 100644
--- a/src/GUI/NewOperations.java
+++ b/src/GUI/NewOperations.java
@@ -1,1004 +1,1005 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import static GUI.MainWindow.Black;
import static GUI.MainWindow.Gray;
import controller.Controller;
import deliver.Deliver;
import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
/**
*
* @author NasK
*/
public class NewOperations extends javax.swing.JDialog {
private Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons2/cog.png"));
//<editor-fold defaultstate="collapsed" desc=" Nombres del los jTextFields ">
private String SINTAX_ORDER = "SINTAX_ORDER";
private String EXEC_COMMAND = "EXEC_COMMAND";
private String SINTAX_COMMAND = "SINTAX_COMMAND";
private String SINTAX_OPERATION_1 = "SINTAX_OPERATION";
private String SINTAX_OPERATION_2 = "SINTAX_OPERATION";
private String BASIC_PROCESS = "BASIC_PROCESS";
private String NEW_PROCESS = "NEW_PROCESS";
private String SINTAX_ASSOC = "SINTAX_ASSOC";
//</editor-fold>
private JOptionPane Err = new JOptionPane();
private JOptionPane Info = new JOptionPane();
/**
* Creates new form NewOperations
*/
public NewOperations(javax.swing.JFrame frame) {
initComponents();
MyinitComponents(frame);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
orderFormat = new javax.swing.JTextField();
orderFormatInsert = new javax.swing.JButton();
orderFormatInfo = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
commandFormatExe = new javax.swing.JTextField();
commandFormatExeInsert = new javax.swing.JButton();
commandFormatExeInfo = new javax.swing.JButton();
commandFormatSintax = new javax.swing.JTextField();
commandFormatSintaxInsert = new javax.swing.JButton();
commandFormatSintaxInfo = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
concatOperationSintax = new javax.swing.JTextField();
concatOperationSintaxInsert = new javax.swing.JButton();
concatOperationSintaxInfo = new javax.swing.JButton();
jSeparator3 = new javax.swing.JSeparator();
jPanel2 = new javax.swing.JPanel();
compAsigOperationSintax = new javax.swing.JTextField();
compAsigOperationSintaxInsert = new javax.swing.JButton();
compAsigOperationSintaxInfo = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
basicProcessingFormat = new javax.swing.JTextField();
basicProcessingFormatInsert = new javax.swing.JButton();
basicProcessingFormatInfo = new javax.swing.JButton();
newProcessingFormat = new javax.swing.JTextField();
newProcessingFormatInsert = new javax.swing.JButton();
newProcessingFormatInfo = new javax.swing.JButton();
jSeparator5 = new javax.swing.JSeparator();
associationFormat = new javax.swing.JTextField();
associationFormatInsert = new javax.swing.JButton();
associationFormatInfo = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
closeButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
jSplitPane1.setDividerLocation(295);
jSplitPane1.setEnabled(false);
jPanel1.setPreferredSize(new java.awt.Dimension(270, 45));
orderFormat.setText("X_ORDEN_SINTAX");
orderFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatActionPerformed(evt);
}
});
orderFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
orderFormatFocusLost(evt);
}
public void focusGained(java.awt.event.FocusEvent evt) {
orderFormatFocusGained(evt);
}
});
orderFormatInsert.setText("Insert");
orderFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInsertActionPerformed(evt);
}
});
orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
orderFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInfoActionPerformed(evt);
}
});
commandFormatExe.setText("C_EJECUTA_COMANDO");
commandFormatExe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeActionPerformed(evt);
}
});
commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatExeFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatExeFocusLost(evt);
}
});
commandFormatExeInsert.setText("Insert");
commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInsertActionPerformed(evt);
}
});
commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInfoActionPerformed(evt);
}
});
commandFormatSintax.setText("C_SINTAXIS_COMANDO");
commandFormatSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxActionPerformed(evt);
}
});
commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusLost(evt);
}
});
commandFormatSintaxInsert.setText("Insert");
commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInsertActionPerformed(evt);
}
});
commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInfoActionPerformed(evt);
}
});
concatOperationSintax.setText("X_OPERACION_SINTAX");
concatOperationSintax.setToolTipText("ADDITION-CONCATENATION");
concatOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxActionPerformed(evt);
}
});
concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusLost(evt);
}
});
concatOperationSintaxInsert.setText("Insert");
concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInsertActionPerformed(evt);
}
});
concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addComponent(jSeparator2)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderFormatInsert))
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatExeInsert))
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatSintaxInsert))
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(concatOperationSintaxInsert)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addContainerGap(39, Short.MAX_VALUE))
+ .addContainerGap(48, Short.MAX_VALUE))
);
jSplitPane1.setLeftComponent(jPanel1);
jPanel2.setPreferredSize(new java.awt.Dimension(270, 45));
compAsigOperationSintax.setText("X_OPERACION_SINTAX");
compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT");
compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxActionPerformed(evt);
}
});
compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusLost(evt);
}
});
compAsigOperationSintaxInsert.setText("Insert");
compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInsertActionPerformed(evt);
}
});
compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInfoActionPerformed(evt);
}
});
basicProcessingFormat.setText("_TRATAR_BASICO");
basicProcessingFormat.setToolTipText("LOGIC AND");
basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatActionPerformed(evt);
}
});
basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusLost(evt);
}
});
basicProcessingFormatInsert.setText("Insert");
basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInsertActionPerformed(evt);
}
});
basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInfoActionPerformed(evt);
}
});
newProcessingFormat.setText("_TRATAR_NUEVO");
newProcessingFormat.setToolTipText("LOGIC OPERATION");
newProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatActionPerformed(evt);
}
});
newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusLost(evt);
}
});
newProcessingFormatInsert.setText("Insert");
newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInsertActionPerformed(evt);
}
});
newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInfoActionPerformed(evt);
}
});
associationFormat.setText("X_ASOCIAR_SINTAX");
associationFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatActionPerformed(evt);
}
});
associationFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
associationFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
associationFormatFocusLost(evt);
}
});
associationFormatInsert.setText("Insert");
associationFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInsertActionPerformed(evt);
}
});
associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
associationFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInfoActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator4)
.addComponent(jSeparator5)
.addComponent(jSeparator6)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(compAsigOperationSintaxInsert)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
- .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
- .addGap(0, 0, Short.MAX_VALUE)
- .addComponent(closeButton))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(associationFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(newProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(basicProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
+ .addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
+ .addGap(0, 0, Short.MAX_VALUE)
+ .addComponent(closeButton)
+ .addGap(21, 21, 21)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(compAsigOperationSintaxInsert))
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(basicProcessingFormatInsert))
.addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(newProcessingFormatInsert))
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(associationFormatInsert))
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(closeButton)
- .addContainerGap())
+ .addContainerGap(19, Short.MAX_VALUE))
);
jSplitPane1.setRightComponent(jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 619, Short.MAX_VALUE)
+ .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, Short.MAX_VALUE)
+ .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
//<editor-fold defaultstate="collapsed" desc=" MyinitComponents ">
private void MyinitComponents(javax.swing.JFrame frame) {
setIconImage(icon);
this.setTitle("New Operations");
this.setModal(true);
this.setLocationRelativeTo(frame);
Deliver.setOrigin(this);
Deliver.setDestination(frame);
orderFormat.setForeground(Gray);
commandFormatExe.setForeground(Gray);
commandFormatSintax.setForeground(Gray);
concatOperationSintax.setForeground(Gray);
compAsigOperationSintax.setForeground(Gray);
basicProcessingFormat.setForeground(Gray);
newProcessingFormat.setForeground(Gray);
associationFormat.setForeground(Gray);
orderFormat.setText(SINTAX_ORDER);
commandFormatExe.setText(EXEC_COMMAND);
commandFormatSintax.setText(SINTAX_COMMAND);
concatOperationSintax.setText(SINTAX_OPERATION_1);
compAsigOperationSintax.setText(SINTAX_OPERATION_2);
basicProcessingFormat.setText(BASIC_PROCESS);
newProcessingFormat.setText(NEW_PROCESS);
associationFormat.setText(SINTAX_ASSOC);
orderFormatInsert.requestFocus();
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Acciones Comunes ">
private void opActions(int Index, JTextField jtf, JButton jb, String preText) {
if (!jtf.getText().equalsIgnoreCase(preText)) {
Object[] what = new Object[1];
what[0] = jtf.getText();
Controller.controller(Index, what);
if (preText.equalsIgnoreCase("")) {
jtf.setForeground(Black);
} else {
jtf.setForeground(Gray);
}
jtf.setText(preText);
jb.requestFocus();
}
}
private void opFocus(JTextField jtf, String preText, Color c, String postText) {
if (jtf.getText().equalsIgnoreCase(preText)) {
jtf.setForeground(c);
jtf.setText(postText);
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" TextField & Buttons ">
//<editor-fold defaultstate="collapsed" desc=" 1.orderFormat ">
private void orderFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatActionPerformed
int Index = Controller.orderFormat;
JTextField jtf = orderFormat;
JButton jb = orderFormatInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_orderFormatActionPerformed
private void orderFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_orderFormatFocusGained
JTextField jtf = orderFormat;
String preText = SINTAX_ORDER;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_orderFormatFocusGained
private void orderFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_orderFormatFocusLost
JTextField jtf = orderFormat;
String preText = "";
Color c = Gray;
String postText = SINTAX_ORDER;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_orderFormatFocusLost
private void orderFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatInsertActionPerformed
int Index = Controller.orderFormat;
JTextField jtf = orderFormat;
JButton jb = orderFormatInsert;
String preText = SINTAX_ORDER;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_orderFormatInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 2.commandFormatExe ">
private void commandFormatExeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeActionPerformed
int Index = Controller.commandFormatExe;
JTextField jtf = commandFormatExe;
JButton jb = commandFormatExeInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_commandFormatExeActionPerformed
private void commandFormatExeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatExeFocusGained
JTextField jtf = commandFormatExe;
String preText = EXEC_COMMAND;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_commandFormatExeFocusGained
private void commandFormatExeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatExeFocusLost
JTextField jtf = commandFormatExe;
String preText = "";
Color c = Gray;
String postText = EXEC_COMMAND;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_commandFormatExeFocusLost
private void commandFormatExeInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeInsertActionPerformed
int Index = Controller.commandFormatExe;
JTextField jtf = commandFormatExe;
JButton jb = commandFormatExeInsert;
String preText = EXEC_COMMAND;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_commandFormatExeInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 3.commandFormatSintax ">
private void commandFormatSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxActionPerformed
int Index = Controller.commandFormatSintax;
JTextField jtf = commandFormatSintax;
JButton jb = commandFormatSintaxInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_commandFormatSintaxActionPerformed
private void commandFormatSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatSintaxFocusGained
JTextField jtf = commandFormatSintax;
String preText = SINTAX_COMMAND;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_commandFormatSintaxFocusGained
private void commandFormatSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_commandFormatSintaxFocusLost
JTextField jtf = commandFormatSintax;
String preText = "";
Color c = Gray;
String postText = SINTAX_COMMAND;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_commandFormatSintaxFocusLost
private void commandFormatSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxInsertActionPerformed
int Index = Controller.commandFormatSintax;
JTextField jtf = commandFormatSintax;
JButton jb = commandFormatSintaxInsert;
String preText = SINTAX_COMMAND;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_commandFormatSintaxInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 4.concatOperationSintax ">
private void concatOperationSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxActionPerformed
int Index = Controller.concatOperationSintax;
JTextField jtf = concatOperationSintax;
JButton jb = concatOperationSintaxInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_concatOperationSintaxActionPerformed
private void concatOperationSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_concatOperationSintaxFocusGained
JTextField jtf = concatOperationSintax;
String preText = SINTAX_OPERATION_1;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_concatOperationSintaxFocusGained
private void concatOperationSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_concatOperationSintaxFocusLost
JTextField jtf = concatOperationSintax;
String preText = "";
Color c = Gray;
String postText = SINTAX_OPERATION_1;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_concatOperationSintaxFocusLost
private void concatOperationSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxInsertActionPerformed
int Index = Controller.concatOperationSintax;
JTextField jtf = concatOperationSintax;
JButton jb = concatOperationSintaxInsert;
String preText = SINTAX_OPERATION_1;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_concatOperationSintaxInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 5.compAsigOperationSintax ">
private void compAsigOperationSintaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxActionPerformed
int Index = Controller.compAsigOperationSintax;
JTextField jtf = compAsigOperationSintax;
JButton jb = compAsigOperationSintaxInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_compAsigOperationSintaxActionPerformed
private void compAsigOperationSintaxFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxFocusGained
JTextField jtf = compAsigOperationSintax;
String preText = SINTAX_OPERATION_2;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_compAsigOperationSintaxFocusGained
private void compAsigOperationSintaxFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxFocusLost
JTextField jtf = compAsigOperationSintax;
String preText = "";
Color c = Gray;
String postText = SINTAX_OPERATION_2;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_compAsigOperationSintaxFocusLost
private void compAsigOperationSintaxInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxInsertActionPerformed
int Index = Controller.compAsigOperationSintax;
JTextField jtf = compAsigOperationSintax;
JButton jb = compAsigOperationSintaxInsert;
String preText = SINTAX_OPERATION_2;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_compAsigOperationSintaxInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 6.basicProcessingFormat ">
private void basicProcessingFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatActionPerformed
int Index = Controller.basicProcessingFormat;
JTextField jtf = basicProcessingFormat;
JButton jb = basicProcessingFormatInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_basicProcessingFormatActionPerformed
private void basicProcessingFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_basicProcessingFormatFocusGained
JTextField jtf = basicProcessingFormat;
String preText = BASIC_PROCESS;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_basicProcessingFormatFocusGained
private void basicProcessingFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_basicProcessingFormatFocusLost
JTextField jtf = basicProcessingFormat;
String preText = "";
Color c = Gray;
String postText = BASIC_PROCESS;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_basicProcessingFormatFocusLost
private void basicProcessingFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatInsertActionPerformed
int Index = Controller.basicProcessingFormat;
JTextField jtf = basicProcessingFormat;
JButton jb = basicProcessingFormatInsert;
String preText = BASIC_PROCESS;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_basicProcessingFormatInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 7.newProcessingFormat ">
private void newProcessingFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatActionPerformed
int Index = Controller.newProcessingFormat;
JTextField jtf = newProcessingFormat;
JButton jb = newProcessingFormatInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_newProcessingFormatActionPerformed
private void newProcessingFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_newProcessingFormatFocusGained
JTextField jtf = newProcessingFormat;
String preText = NEW_PROCESS;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_newProcessingFormatFocusGained
private void newProcessingFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_newProcessingFormatFocusLost
JTextField jtf = newProcessingFormat;
String preText = "";
Color c = Gray;
String postText = NEW_PROCESS;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_newProcessingFormatFocusLost
private void newProcessingFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatInsertActionPerformed
int Index = Controller.newProcessingFormat;
JTextField jtf = newProcessingFormat;
JButton jb = newProcessingFormatInsert;
String preText = NEW_PROCESS;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_newProcessingFormatInsertActionPerformed
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" 8.associationFormat ">
private void associationFormatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatActionPerformed
int Index = Controller.associationFormat;
JTextField jtf = associationFormat;
JButton jb = associationFormatInsert;
String preText = "";
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_associationFormatActionPerformed
private void associationFormatFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_associationFormatFocusGained
JTextField jtf = associationFormat;
String preText = SINTAX_ASSOC;
Color c = Black;
String postText = "";
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_associationFormatFocusGained
private void associationFormatFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_associationFormatFocusLost
JTextField jtf = associationFormat;
String preText = "";
Color c = Gray;
String postText = SINTAX_ASSOC;
opFocus(jtf, preText, c, postText);
}//GEN-LAST:event_associationFormatFocusLost
private void associationFormatInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatInsertActionPerformed
int Index = Controller.associationFormat;
JTextField jtf = associationFormat;
JButton jb = associationFormatInsert;
String preText = SINTAX_ASSOC;
opActions(Index, jtf, jb, preText);
}//GEN-LAST:event_associationFormatInsertActionPerformed
//</editor-fold>
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" FailureManager ">
public void showError(String error) {
String[] es = error.split("@");
String Text = "<html><b>Input example:</b><br>"
+ "<i>" + es[0] + "</i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i>" + es[1] + "</i></html>";
Err.showMessageDialog(this, Text, "Invalid Input format", JOptionPane.ERROR_MESSAGE);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=" Info Buttons ">
public void showInfo(String info) {
Info.showMessageDialog(this, info, "Format info", JOptionPane.INFORMATION_MESSAGE);
}
private void orderFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderFormatInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> [C],[S],[I],[D],[U],[Q] </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^X_ORDEN_SINTAX.”[C],[S],[I],[D],[U],[Q]” </i></html>";
showInfo(Text);
}//GEN-LAST:event_orderFormatInfoActionPerformed
private void commandFormatExeInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatExeInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> [-c CENTRAL] -u USUARIO_EOC [–x SERVICIO] –e COMANDO "
+ "[-t TEMPORIZACION] [-s TAMANO] [-p PATRONES] [-m MAQUINA] "
+ "[-r RESPALDO] </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^C_EJECUTA_COMANDO.”[-c CENTRAL] -u USUARIO_EOC [–x SERVICIO]"
+ " –e COMANDO [-t TEMPORIZACION] [-s TAMANO] [-p PATRONES] "
+ "[-m MAQUINA] [-r RESPALDO]” </i></html>";
showInfo(Text);
}//GEN-LAST:event_commandFormatExeInfoActionPerformed
private void commandFormatSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandFormatSintaxInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> -u OMEGAAXE –t X: MY_TIEMPO –e SASTP –r NO </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^C_EJECUTA_COMANDO.”-u OMEGAAXE –t X: MY_TIEMPO –e SASTP "
+ "–r NO” </i></html>";
showInfo(Text);
}//GEN-LAST:event_commandFormatSintaxInfoActionPerformed
private void concatOperationSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_concatOperationSintaxInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> XH:VAR_DATE SH:FECHA XH:CASI_FECHA </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^X_OPERACION_SINTAX.”XH:VAR_DATE + SH:FECHA = "
+ "XH:CASI_FECHA” </i></html>";
showInfo(Text);
}//GEN-LAST:event_concatOperationSintaxInfoActionPerformed
private void compAsigOperationSintaxInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_compAsigOperationSintaxInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> XH:VAR_UNO != EH:ORIGEN XH:VAR_TRES XH:VAR_DOS XH:ESLOGAN </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^X_OPERACION_SINTAX.”XH:VAR_UNO != EH:ORIGEN # XH:VAR_TRES"
+ " = XH:ESLOGAN # XH:VAR_DOS = XH:ESLOGAN” </i></html>";
showInfo(Text);
}//GEN-LAST:event_compAsigOperationSintaxInfoActionPerformed
private void basicProcessingFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_basicProcessingFormatInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> insert XH:VAR_VACIA , EH:ORIGEN XH:CONDI , FALSE </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^I_TRATAR_INSERT.”XH:VAR_VACIA , EH:ORIGEN # XH:CONDI , "
+ "FALSE” </i></html>";
showInfo(Text);
}//GEN-LAST:event_basicProcessingFormatInfoActionPerformed
private void newProcessingFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newProcessingFormatInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> insert EH:ORIGEN == ‘MI_CENTRAL’ A XN:NUMERO >= EN:SECUENCIA B "
+ "XN:NUM > 100 C ; !(C | B) & A </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^I_TRATAR_INSERT.”EH:ORIGEN == ‘MI_CENTRAL’ = A ; "
+ "XN:NUMERO >= EN:SECUENCIA = B ; XN:NUM > 100 = C # !(C | B) "
+ "& A” </i></html>";
showInfo(Text);
}//GEN-LAST:event_newProcessingFormatInfoActionPerformed
private void associationFormatInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationFormatInfoActionPerformed
String Text = "<html><b>Input example:</b><br>"
+ "<i> REGIS_A ; CAUSA_A </i><br><br>"
+ "<b>Output example:</b><br>"
+ "<i> %^X_ASOCIAR_SINTAX.\"REGIS_A # CAUSA_A\" </i></html>";
showInfo(Text);
}//GEN-LAST:event_associationFormatInfoActionPerformed
//</editor-fold>
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
this.dispose();
}//GEN-LAST:event_closeButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField associationFormat;
private javax.swing.JButton associationFormatInfo;
private javax.swing.JButton associationFormatInsert;
private javax.swing.JTextField basicProcessingFormat;
private javax.swing.JButton basicProcessingFormatInfo;
private javax.swing.JButton basicProcessingFormatInsert;
private javax.swing.JButton closeButton;
private javax.swing.JTextField commandFormatExe;
private javax.swing.JButton commandFormatExeInfo;
private javax.swing.JButton commandFormatExeInsert;
private javax.swing.JTextField commandFormatSintax;
private javax.swing.JButton commandFormatSintaxInfo;
private javax.swing.JButton commandFormatSintaxInsert;
private javax.swing.JTextField compAsigOperationSintax;
private javax.swing.JButton compAsigOperationSintaxInfo;
private javax.swing.JButton compAsigOperationSintaxInsert;
private javax.swing.JTextField concatOperationSintax;
private javax.swing.JButton concatOperationSintaxInfo;
private javax.swing.JButton concatOperationSintaxInsert;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTextField newProcessingFormat;
private javax.swing.JButton newProcessingFormatInfo;
private javax.swing.JButton newProcessingFormatInsert;
private javax.swing.JTextField orderFormat;
private javax.swing.JButton orderFormatInfo;
private javax.swing.JButton orderFormatInsert;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
orderFormat = new javax.swing.JTextField();
orderFormatInsert = new javax.swing.JButton();
orderFormatInfo = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
commandFormatExe = new javax.swing.JTextField();
commandFormatExeInsert = new javax.swing.JButton();
commandFormatExeInfo = new javax.swing.JButton();
commandFormatSintax = new javax.swing.JTextField();
commandFormatSintaxInsert = new javax.swing.JButton();
commandFormatSintaxInfo = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
concatOperationSintax = new javax.swing.JTextField();
concatOperationSintaxInsert = new javax.swing.JButton();
concatOperationSintaxInfo = new javax.swing.JButton();
jSeparator3 = new javax.swing.JSeparator();
jPanel2 = new javax.swing.JPanel();
compAsigOperationSintax = new javax.swing.JTextField();
compAsigOperationSintaxInsert = new javax.swing.JButton();
compAsigOperationSintaxInfo = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
basicProcessingFormat = new javax.swing.JTextField();
basicProcessingFormatInsert = new javax.swing.JButton();
basicProcessingFormatInfo = new javax.swing.JButton();
newProcessingFormat = new javax.swing.JTextField();
newProcessingFormatInsert = new javax.swing.JButton();
newProcessingFormatInfo = new javax.swing.JButton();
jSeparator5 = new javax.swing.JSeparator();
associationFormat = new javax.swing.JTextField();
associationFormatInsert = new javax.swing.JButton();
associationFormatInfo = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
closeButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
jSplitPane1.setDividerLocation(295);
jSplitPane1.setEnabled(false);
jPanel1.setPreferredSize(new java.awt.Dimension(270, 45));
orderFormat.setText("X_ORDEN_SINTAX");
orderFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatActionPerformed(evt);
}
});
orderFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
orderFormatFocusLost(evt);
}
public void focusGained(java.awt.event.FocusEvent evt) {
orderFormatFocusGained(evt);
}
});
orderFormatInsert.setText("Insert");
orderFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInsertActionPerformed(evt);
}
});
orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
orderFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInfoActionPerformed(evt);
}
});
commandFormatExe.setText("C_EJECUTA_COMANDO");
commandFormatExe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeActionPerformed(evt);
}
});
commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatExeFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatExeFocusLost(evt);
}
});
commandFormatExeInsert.setText("Insert");
commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInsertActionPerformed(evt);
}
});
commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInfoActionPerformed(evt);
}
});
commandFormatSintax.setText("C_SINTAXIS_COMANDO");
commandFormatSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxActionPerformed(evt);
}
});
commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusLost(evt);
}
});
commandFormatSintaxInsert.setText("Insert");
commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInsertActionPerformed(evt);
}
});
commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInfoActionPerformed(evt);
}
});
concatOperationSintax.setText("X_OPERACION_SINTAX");
concatOperationSintax.setToolTipText("ADDITION-CONCATENATION");
concatOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxActionPerformed(evt);
}
});
concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusLost(evt);
}
});
concatOperationSintaxInsert.setText("Insert");
concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInsertActionPerformed(evt);
}
});
concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addComponent(jSeparator2)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderFormatInsert))
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatExeInsert))
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatSintaxInsert))
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(concatOperationSintaxInsert)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))
);
jSplitPane1.setLeftComponent(jPanel1);
jPanel2.setPreferredSize(new java.awt.Dimension(270, 45));
compAsigOperationSintax.setText("X_OPERACION_SINTAX");
compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT");
compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxActionPerformed(evt);
}
});
compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusLost(evt);
}
});
compAsigOperationSintaxInsert.setText("Insert");
compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInsertActionPerformed(evt);
}
});
compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInfoActionPerformed(evt);
}
});
basicProcessingFormat.setText("_TRATAR_BASICO");
basicProcessingFormat.setToolTipText("LOGIC AND");
basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatActionPerformed(evt);
}
});
basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusLost(evt);
}
});
basicProcessingFormatInsert.setText("Insert");
basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInsertActionPerformed(evt);
}
});
basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInfoActionPerformed(evt);
}
});
newProcessingFormat.setText("_TRATAR_NUEVO");
newProcessingFormat.setToolTipText("LOGIC OPERATION");
newProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatActionPerformed(evt);
}
});
newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusLost(evt);
}
});
newProcessingFormatInsert.setText("Insert");
newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInsertActionPerformed(evt);
}
});
newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInfoActionPerformed(evt);
}
});
associationFormat.setText("X_ASOCIAR_SINTAX");
associationFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatActionPerformed(evt);
}
});
associationFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
associationFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
associationFormatFocusLost(evt);
}
});
associationFormatInsert.setText("Insert");
associationFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInsertActionPerformed(evt);
}
});
associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
associationFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInfoActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator4)
.addComponent(jSeparator5)
.addComponent(jSeparator6)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(compAsigOperationSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(closeButton))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(associationFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(newProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(basicProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(compAsigOperationSintaxInsert))
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(basicProcessingFormatInsert))
.addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(newProcessingFormatInsert))
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(associationFormatInsert))
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(closeButton)
.addContainerGap())
);
jSplitPane1.setRightComponent(jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 619, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
orderFormat = new javax.swing.JTextField();
orderFormatInsert = new javax.swing.JButton();
orderFormatInfo = new javax.swing.JButton();
jSeparator1 = new javax.swing.JSeparator();
commandFormatExe = new javax.swing.JTextField();
commandFormatExeInsert = new javax.swing.JButton();
commandFormatExeInfo = new javax.swing.JButton();
commandFormatSintax = new javax.swing.JTextField();
commandFormatSintaxInsert = new javax.swing.JButton();
commandFormatSintaxInfo = new javax.swing.JButton();
jSeparator2 = new javax.swing.JSeparator();
concatOperationSintax = new javax.swing.JTextField();
concatOperationSintaxInsert = new javax.swing.JButton();
concatOperationSintaxInfo = new javax.swing.JButton();
jSeparator3 = new javax.swing.JSeparator();
jPanel2 = new javax.swing.JPanel();
compAsigOperationSintax = new javax.swing.JTextField();
compAsigOperationSintaxInsert = new javax.swing.JButton();
compAsigOperationSintaxInfo = new javax.swing.JButton();
jSeparator4 = new javax.swing.JSeparator();
basicProcessingFormat = new javax.swing.JTextField();
basicProcessingFormatInsert = new javax.swing.JButton();
basicProcessingFormatInfo = new javax.swing.JButton();
newProcessingFormat = new javax.swing.JTextField();
newProcessingFormatInsert = new javax.swing.JButton();
newProcessingFormatInfo = new javax.swing.JButton();
jSeparator5 = new javax.swing.JSeparator();
associationFormat = new javax.swing.JTextField();
associationFormatInsert = new javax.swing.JButton();
associationFormatInfo = new javax.swing.JButton();
jSeparator6 = new javax.swing.JSeparator();
closeButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
setResizable(false);
jSplitPane1.setDividerLocation(295);
jSplitPane1.setEnabled(false);
jPanel1.setPreferredSize(new java.awt.Dimension(270, 45));
orderFormat.setText("X_ORDEN_SINTAX");
orderFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatActionPerformed(evt);
}
});
orderFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
orderFormatFocusLost(evt);
}
public void focusGained(java.awt.event.FocusEvent evt) {
orderFormatFocusGained(evt);
}
});
orderFormatInsert.setText("Insert");
orderFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInsertActionPerformed(evt);
}
});
orderFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
orderFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
orderFormatInfoActionPerformed(evt);
}
});
commandFormatExe.setText("C_EJECUTA_COMANDO");
commandFormatExe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeActionPerformed(evt);
}
});
commandFormatExe.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatExeFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatExeFocusLost(evt);
}
});
commandFormatExeInsert.setText("Insert");
commandFormatExeInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInsertActionPerformed(evt);
}
});
commandFormatExeInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatExeInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatExeInfoActionPerformed(evt);
}
});
commandFormatSintax.setText("C_SINTAXIS_COMANDO");
commandFormatSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxActionPerformed(evt);
}
});
commandFormatSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
commandFormatSintaxFocusLost(evt);
}
});
commandFormatSintaxInsert.setText("Insert");
commandFormatSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInsertActionPerformed(evt);
}
});
commandFormatSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
commandFormatSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
commandFormatSintaxInfoActionPerformed(evt);
}
});
concatOperationSintax.setText("X_OPERACION_SINTAX");
concatOperationSintax.setToolTipText("ADDITION-CONCATENATION");
concatOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxActionPerformed(evt);
}
});
concatOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
concatOperationSintaxFocusLost(evt);
}
});
concatOperationSintaxInsert.setText("Insert");
concatOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInsertActionPerformed(evt);
}
});
concatOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
concatOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
concatOperationSintaxInfoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator3)
.addComponent(jSeparator2)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(orderFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(orderFormatInsert))
.addComponent(orderFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatExe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatExeInsert))
.addComponent(commandFormatExeInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(commandFormatSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(commandFormatSintaxInsert))
.addComponent(commandFormatSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(concatOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(concatOperationSintaxInsert)
.addComponent(concatOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(48, Short.MAX_VALUE))
);
jSplitPane1.setLeftComponent(jPanel1);
jPanel2.setPreferredSize(new java.awt.Dimension(270, 45));
compAsigOperationSintax.setText("X_OPERACION_SINTAX");
compAsigOperationSintax.setToolTipText("COMPARISON-ASSIGNMENT");
compAsigOperationSintax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxActionPerformed(evt);
}
});
compAsigOperationSintax.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
compAsigOperationSintaxFocusLost(evt);
}
});
compAsigOperationSintaxInsert.setText("Insert");
compAsigOperationSintaxInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInsertActionPerformed(evt);
}
});
compAsigOperationSintaxInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
compAsigOperationSintaxInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
compAsigOperationSintaxInfoActionPerformed(evt);
}
});
basicProcessingFormat.setText("_TRATAR_BASICO");
basicProcessingFormat.setToolTipText("LOGIC AND");
basicProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatActionPerformed(evt);
}
});
basicProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
basicProcessingFormatFocusLost(evt);
}
});
basicProcessingFormatInsert.setText("Insert");
basicProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInsertActionPerformed(evt);
}
});
basicProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
basicProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
basicProcessingFormatInfoActionPerformed(evt);
}
});
newProcessingFormat.setText("_TRATAR_NUEVO");
newProcessingFormat.setToolTipText("LOGIC OPERATION");
newProcessingFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatActionPerformed(evt);
}
});
newProcessingFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
newProcessingFormatFocusLost(evt);
}
});
newProcessingFormatInsert.setText("Insert");
newProcessingFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInsertActionPerformed(evt);
}
});
newProcessingFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
newProcessingFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newProcessingFormatInfoActionPerformed(evt);
}
});
associationFormat.setText("X_ASOCIAR_SINTAX");
associationFormat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatActionPerformed(evt);
}
});
associationFormat.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
associationFormatFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
associationFormatFocusLost(evt);
}
});
associationFormatInsert.setText("Insert");
associationFormatInsert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInsertActionPerformed(evt);
}
});
associationFormatInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/information.png"))); // NOI18N
associationFormatInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
associationFormatInfoActionPerformed(evt);
}
});
closeButton.setText("Close");
closeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closeButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator4)
.addComponent(jSeparator5)
.addComponent(jSeparator6)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(compAsigOperationSintaxInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(associationFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(newProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(basicProcessingFormatInsert)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(closeButton)
.addGap(21, 21, 21)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(compAsigOperationSintax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(compAsigOperationSintaxInsert))
.addComponent(compAsigOperationSintaxInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(basicProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(basicProcessingFormatInsert))
.addComponent(basicProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(newProcessingFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(newProcessingFormatInsert))
.addComponent(newProcessingFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(associationFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(associationFormatInsert))
.addComponent(associationFormatInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(closeButton)
.addContainerGap(19, Short.MAX_VALUE))
);
jSplitPane1.setRightComponent(jPanel2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/net/sf/freecol/client/gui/option/RangeOptionUI.java b/src/net/sf/freecol/client/gui/option/RangeOptionUI.java
index 4fdfa2a8d..3c8ab7cd0 100644
--- a/src/net/sf/freecol/client/gui/option/RangeOptionUI.java
+++ b/src/net/sf/freecol/client/gui/option/RangeOptionUI.java
@@ -1,155 +1,156 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.gui.option;
import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.sf.freecol.common.option.Option;
import net.sf.freecol.common.option.RangeOption;
/**
* This class provides visualization for an {@link RangeOption}. In order to
* enable values to be both seen and changed.
*/
public final class RangeOptionUI extends JPanel implements OptionUpdater, PropertyChangeListener {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(RangeOptionUI.class.getName());
private final RangeOption option;
private final JSlider slider;
private int originalValue;
/**
* Creates a new <code>RangeOptionUI</code> for the given
* <code>RangeOption</code>.
*
* @param option The <code>RangeOption</code> to make a user interface
* for.
*/
public RangeOptionUI(final RangeOption option, boolean editable) {
setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),
option.getName()));
this.option = option;
+ this.originalValue = option.getValue();
String name = option.getName();
String description = option.getShortDescription();
//JLabel label = new JLabel(name, JLabel.LEFT);
//label.setToolTipText((description != null) ? description : name);
//add(label);
String[] strings = option.getItemValues().values().toArray(new String[0]);
slider = new JSlider(JSlider.HORIZONTAL, 0, strings.length - 1, option.getValueRank());
Hashtable<Integer, JComponent> labels = new Hashtable<Integer, JComponent>();
for (int i = 0; i < strings.length; i++) {
labels.put(new Integer(i), new JLabel(strings[i]));
}
slider.setLabelTable(labels);
slider.setValue(option.getValueRank());
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setExtent(0);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setPreferredSize(new Dimension(500, 50));
slider.setToolTipText((description != null) ? description : name);
add(slider);
slider.setEnabled(editable);
slider.setOpaque(false);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (option.isPreviewEnabled()) {
final int value = slider.getValue();
if (option.getValue() != value) {
option.setValueRank(value);
}
}
}
});
option.addPropertyChangeListener(this);
setOpaque(false);
}
/**
* Rollback to the original value.
*
* This method gets called so that changes made to options with
* {@link Option#isPreviewEnabled()} is rolled back
* when an option dialoag has been cancelled.
*/
public void rollback() {
option.setValue(originalValue);
}
/**
* Unregister <code>PropertyChangeListener</code>s.
*/
public void unregister() {
option.removePropertyChangeListener(this);
}
/**
* Updates this UI with the new data from the option.
*
* @param event The event.
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getPropertyName().equals("value")) {
final int value = ((Integer) event.getNewValue()).intValue();
if (value != slider.getValue()) {
slider.setValue(value);
originalValue = value;
}
}
}
/**
* Updates the value of the {@link Option} this object keeps.
*/
public void updateOption() {
option.setValueRank(slider.getValue());
}
/**
* Reset with the value from the option.
*/
public void reset() {
slider.setValue(option.getValueRank());
}
}
| true | true | public RangeOptionUI(final RangeOption option, boolean editable) {
setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),
option.getName()));
this.option = option;
String name = option.getName();
String description = option.getShortDescription();
//JLabel label = new JLabel(name, JLabel.LEFT);
//label.setToolTipText((description != null) ? description : name);
//add(label);
String[] strings = option.getItemValues().values().toArray(new String[0]);
slider = new JSlider(JSlider.HORIZONTAL, 0, strings.length - 1, option.getValueRank());
Hashtable<Integer, JComponent> labels = new Hashtable<Integer, JComponent>();
for (int i = 0; i < strings.length; i++) {
labels.put(new Integer(i), new JLabel(strings[i]));
}
slider.setLabelTable(labels);
slider.setValue(option.getValueRank());
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setExtent(0);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setPreferredSize(new Dimension(500, 50));
slider.setToolTipText((description != null) ? description : name);
add(slider);
slider.setEnabled(editable);
slider.setOpaque(false);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (option.isPreviewEnabled()) {
final int value = slider.getValue();
if (option.getValue() != value) {
option.setValueRank(value);
}
}
}
});
option.addPropertyChangeListener(this);
setOpaque(false);
}
| public RangeOptionUI(final RangeOption option, boolean editable) {
setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK),
option.getName()));
this.option = option;
this.originalValue = option.getValue();
String name = option.getName();
String description = option.getShortDescription();
//JLabel label = new JLabel(name, JLabel.LEFT);
//label.setToolTipText((description != null) ? description : name);
//add(label);
String[] strings = option.getItemValues().values().toArray(new String[0]);
slider = new JSlider(JSlider.HORIZONTAL, 0, strings.length - 1, option.getValueRank());
Hashtable<Integer, JComponent> labels = new Hashtable<Integer, JComponent>();
for (int i = 0; i < strings.length; i++) {
labels.put(new Integer(i), new JLabel(strings[i]));
}
slider.setLabelTable(labels);
slider.setValue(option.getValueRank());
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setExtent(0);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setPreferredSize(new Dimension(500, 50));
slider.setToolTipText((description != null) ? description : name);
add(slider);
slider.setEnabled(editable);
slider.setOpaque(false);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (option.isPreviewEnabled()) {
final int value = slider.getValue();
if (option.getValue() != value) {
option.setValueRank(value);
}
}
}
});
option.addPropertyChangeListener(this);
setOpaque(false);
}
|
diff --git a/src/ribbonserver/RibbonProtocol.java b/src/ribbonserver/RibbonProtocol.java
index af1920e..46797b2 100644
--- a/src/ribbonserver/RibbonProtocol.java
+++ b/src/ribbonserver/RibbonProtocol.java
@@ -1,770 +1,770 @@
/**
* This file is part of RibbonServer application (check README).
* Copyright (C) 2012-2013 Stanislav Nepochatov
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
package ribbonserver;
/**
* Ribbon protocol server side class
* @author Stanislav Nepochatov
* @since RibbonServer a1
*/
public class RibbonProtocol {
private String LOG_ID = "ПРОТОКОЛ";
/**
* Tail of protocol result which should be delivered to all peers;
* @since RibbonServer a1
*/
public String BROADCAST_TAIL;
/**
* Type of broadcasting;
* @since RibbonServer a1
*/
public CONNECTION_TYPES BROADCAST_TYPE;
/**
* Remote session flag.
*/
private Boolean IS_REMOTE = false;
/**
* Default constructor.
* @param upperThread given session thread to link with;
* @since RibbonServer a1
*/
RibbonProtocol(SessionManager.SessionThread upperThread) {
InitProtocol();
CURR_SESSION = upperThread;
}
/**
* Link to upper level thread
* @since RibbonServer a1
*/
private SessionManager.SessionThread CURR_SESSION;
/**
* Protocol revision digit.
* @since RibbonServer a1
*/
private Integer INT_VERSION = 2;
/**
* String protocol revision version.
* @since RibbonServer a1
*/
private String STR_VERSION = RibbonServer.RIBBON_VER;
/**
* Connection type enumeration.
* @since RibbonServer a1
*/
public enum CONNECTION_TYPES {
/**
* NULL connection: peer didn't call RIBBON_NCTL_INIT: yet.
*/
NULL,
/**
* CLIENT connection for all user applications.
*/
CLIENT,
/**
* CONTROL connection for all adm applications.
*/
CONTROL,
/**
* Connection for any application.
*/
ANY
};
/**
* Current type of connection.
* @since RibbonServer a1
*/
public CONNECTION_TYPES CURR_TYPE = CONNECTION_TYPES.NULL;
/**
* ArrayList of commands objects.
* @since RibbonServer a1
*/
private java.util.ArrayList<CommandLet> RIBBON_COMMANDS = new java.util.ArrayList<CommandLet>();
/**
* Command template class.
* @since RibbonServer a1
*/
private class CommandLet {
/**
* Default constroctor.
* @param givenName name of command;
* @param givenType type of connections which may use this command;
* @since RibbonServer a1
*/
CommandLet(String givenName, CONNECTION_TYPES givenType) {
this.COMMAND_NAME = givenName;
this.COMM_TYPE = givenType;
}
/**
* Name of command.
* @since RibbonServer a1
*/
public String COMMAND_NAME;
/**
* Type of connections which may use this command.
* @since RibbonServer a1
*/
public CONNECTION_TYPES COMM_TYPE;
/**
* Main command body.
* @param args arguments from application <i>(may be in CSV format)</i>;
* @return command answer;
* @since RibbonServer a1
*/
public String exec(String args) {return "";};
}
/**
* Init protocol and load commands.
* @since RibbonServer a1
*/
private void InitProtocol() {
/** CONNECTION CONTROL COMMANDS [LEVEL_0 SUPPORT] **/
/**
* RIBBON_NCTL_INIT: commandlet
* Client and others application send this command to register
* this connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_INIT", CONNECTION_TYPES.NULL) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
if (CURR_TYPE == CONNECTION_TYPES.NULL) {
if (parsedArgs[1].equals(STR_VERSION)) {
try {
if (parsedArgs[0].equals("ANY") || parsedArgs[0].equals("NULL")) {
throw new IllegalArgumentException();
}
CURR_TYPE = CONNECTION_TYPES.valueOf(parsedArgs[0]);
if (!parsedArgs[2].equals(System.getProperty("file.encoding"))) {
RibbonServer.logAppend(LOG_ID, 2, "мережева сесія вимогає іншої кодової сторінки:" + parsedArgs[2]);
CURR_SESSION.setReaderEncoding(parsedArgs[2]);
}
return "OK:\nRIBBON_GCTL_FORCE_LOGIN:";
} catch (IllegalArgumentException ex) {
return "RIBBON_ERROR:Невідомий тип з'єднання!";
}
} else {
return "RIBBON_ERROR:Невідомий ідентефікатор протокола.";
}
} else {
return "RIBBON_WARNING:З'єднання вже ініціьовано!";
}
}
});
/**
* RIBBON_NCTL_LOGIN: commandlet
* Client and other applications send this command to login user.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (!RibbonServer.ACCESS_ALLOW_MULTIPLIE_LOGIN && SessionManager.isAlreadyLogined(parsedArgs[0])) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " вже увійшов до системи!\nRIBBON_GCTL_FORCE_LOGIN:";
}
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " увійшов до системи.");
if (RibbonServer.CONTROL_IS_PRESENT == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "ініційовано контроль системи!");
RibbonServer.CONTROL_IS_PRESENT = true;
}
}
CURR_SESSION.USER_NAME = parsedArgs[0];
if (RibbonServer.ACCESS_ALLOW_SESSIONS) {
CURR_SESSION.CURR_ENTRY = SessionManager.createSessionEntry(parsedArgs[0]);
CURR_SESSION.setSessionName();
return "OK:" + CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
} else {
return "OK:";
}
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_ID: commandlet
* Find out session ID.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_ID", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
} else if (CURR_SESSION.CURR_ENTRY == null) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
return CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
}
}
});
/**
* RIBBON_NCTL_RESUME: commandlet
* Resume session by given hash id.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_RESUME", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
}
SessionManager.SessionEntry exicted = SessionManager.getUserBySessionEntry(args);
if (exicted == null) {
return "RIBBON_GCTL_FORCE_LOGIN:";
} else {
String returned = AccessHandler.PROC_RESUME_USER(exicted);
if (returned == null) {
SessionManager.reniewEntry(exicted);
CURR_SESSION.USER_NAME = exicted.SESSION_USER_NAME;
CURR_SESSION.CURR_ENTRY = exicted;
CURR_SESSION.setSessionName();
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
}
});
/**
* RIBBON_NCTL_REM_LOGIN: commandlet
* Remote login command.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_REM_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_REMOTE && !IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " видалено увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " видалено увійшов до системи.");
}
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_USERNAME: commandlet
* Get current session username.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_USERNAME", CONNECTION_TYPES.ANY) {
public String exec(String args) {
if (CURR_SESSION.USER_NAME != null) {
return "OK:" + CURR_SESSION.USER_NAME;
} else {
return "RIBBON_ERROR:Вхід до системи не виконано!";
}
}
});
/**
* RIBBON_NCTL_SET_REMOTE_MODE: commandlet
* Set remote flag of this session.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_SET_REMOTE_MODE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!RibbonServer.ACCESS_ALLOW_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (!AccessHandler.isUserIsMemberOf(CURR_SESSION.USER_NAME, RibbonServer.ACCESS_REMOTE_GROUP)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
IS_REMOTE = "1".equals(args) ? true : false;
if (IS_REMOTE) {
RibbonServer.logAppend(LOG_ID, 3, "увімкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
} else {
RibbonServer.logAppend(LOG_ID, 3, "вимкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
}
return "OK:" + (IS_REMOTE ? "1" : "0");
}
});
/**
* RIBBON_NCTL_ACCESS_CONTEXT: commandlet
* Change access mode of next command.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to process() method directly!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_ACCESS_CONTEXT", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
- } else if (!RibbonServer.ACCESS_ALLOW_REMOTE && !IS_REMOTE) {
+ } else if (!IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
UserClasses.UserEntry overUser = AccessHandler.getEntryByName(Generic.CsvFormat.commonParseLine(args, 1)[0]);
if (overUser == null) {
return "RIBBON_ERROR:Користувача не знайдено!";
} else if (!overUser.IS_ENABLED) {
return "RIBBON_ERROR:Користувача заблоковано!";
}
String oldUserName = CURR_SESSION.USER_NAME;
CURR_SESSION.USER_NAME = overUser.USER_NAME;
CURR_SESSION.outStream.println("PROCEED:");
String subResult = null;
try {
subResult = process(CURR_SESSION.inStream.readLine());
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "неможливо прочитати дані з сокету!");
SessionManager.closeSession(CURR_SESSION);
}
CURR_SESSION.USER_NAME = oldUserName;
return subResult;
}
});
/**
* RIBBON_NCTL_CLOSE: commandlet
* Exit command to close connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_CLOSE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && SessionManager.hasOtherControl(CURR_SESSION) == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "контроль над системою завершено!");
RibbonServer.CONTROL_IS_PRESENT = false;
}
return "COMMIT_CLOSE:";
}
});
/** GENERAL PROTOCOL STACK [LEVEL_1 SUPPORT] **/
/**
* RIBBON_GET_DIRS: commandlet
* Return all dirs to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_DIRS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Directories.PROC_GET_DIRS();
}
});
/**
* RIBBON_GET_PSEUDO: commandlet
* Return csv list of pseudo directories which user may use.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
return Directories.PROC_GET_PSEUDO(CURR_SESSION.USER_NAME);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_TAGS: commandlet
* Return all tags to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_TAGS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_GET_TAGS();
}
});
/**
* RIBBON_LOAD_BASE_FROM_INDEX: commandlet
* Return all messages which were released later than specified index.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_LOAD_BASE_FROM_INDEX", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_LOAD_BASE_FROM_INDEX(args);
}
});
/**
* RIBBON_POST_MESSAGE: commandlet
* Post message to the system.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.Message recievedMessage = new MessageClasses.Message();
recievedMessage.createMessageForPost(args);
recievedMessage.AUTHOR = CURR_SESSION.USER_NAME;
Boolean collectMessage = true;
StringBuffer messageBuffer = new StringBuffer();
String inLine;
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
recievedMessage.CONTENT = messageBuffer.toString();
String answer = Procedures.PROC_POST_MESSAGE(recievedMessage);
if (answer.equals("OK:")) {
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + recievedMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
return answer;
}
});
/**
* RIBBON_POST_MESSAGE_BY_PSEUDO: commandlet
* Post message from remote interface to the system by using pseudo directory.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to RIBBON_POST_MESSAGE commandlet
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE_BY_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
java.util.ArrayList<String[]> parsed = Generic.CsvFormat.complexParseLine(args, 4, 1);
Directories.PseudoDirEntry currPostPseudo = Directories.getPseudoDir(parsed.get(0)[0]);
if (currPostPseudo == null) {
return "RIBBON_ERROR:Псевдонапрямок " + parsed.get(0)[0] + " не існує.";
}
String[] postDirs = currPostPseudo.getinternalDirectories();
String commandToPost = "RIBBON_POST_MESSAGE:-1," + args.replace("{" + currPostPseudo.PSEUDO_DIR_NAME + "}", Generic.CsvFormat.renderGroup(postDirs));
RibbonServer.logAppend(LOG_ID, 3, "додано повідомлення через псевдонапрямок '" + currPostPseudo.PSEUDO_DIR_NAME + "'");
return process(commandToPost);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_MESSAGE: commandlet
* Retrieve message body.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
String givenDir = parsedArgs[0];
String givenIndex = parsedArgs[1];
StringBuffer returnedMessage = new StringBuffer();
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, givenDir, 0) == false) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + givenDir;
}
String dirPath = Directories.getDirPath(givenDir);
if (dirPath == null) {
return "RIBBON_ERROR:Напрямок " + givenDir + " не існує!";
} else {
try {
java.io.BufferedReader messageReader = new java.io.BufferedReader(new java.io.FileReader(dirPath + givenIndex));
while (messageReader.ready()) {
returnedMessage.append(messageReader.readLine());
returnedMessage.append("\n");
}
return returnedMessage.append("END:").toString();
} catch (java.io.FileNotFoundException ex) {
return "RIBBON_ERROR:Повідмолення не існує!";
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "помилка зчитування повідомлення " + givenDir + ":" + givenIndex);
return "RIBBON_ERROR:Помилка виконання команди!";
}
}
}
});
/**
* RIBBON_MODIFY_MESSAGE: commandlet
* Modify text of existing message.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_MODIFY_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
StringBuffer messageBuffer = new StringBuffer();
String inLine;
Boolean collectMessage = true;
String[] parsedArgs = Generic.CsvFormat.splitCsv(args);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
MessageClasses.Message modTemplate = new MessageClasses.Message();
modTemplate.createMessageForModify(parsedArgs[1]);
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
modTemplate.CONTENT = messageBuffer.toString();
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
Integer oldIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2);
Integer newIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, modTemplate.DIRS, 1);
if ((CURR_SESSION.USER_NAME.equals(matchedEntry.AUTHOR) && (newIntFlag == null)) || ((oldIntFlag == null) && (newIntFlag == null))) {
for (Integer dirIndex = 0; dirIndex < matchedEntry.DIRS.length; dirIndex++) {
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, matchedEntry.DIRS[dirIndex], 1) == true) {
continue;
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[dirIndex] + ".";
}
}
Procedures.PROC_MODIFY_MESSAGE(matchedEntry, modTemplate);
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
if (oldIntFlag != null) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[oldIntFlag] + ".";
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + modTemplate.DIRS[newIntFlag] + ".";
}
}
}
});
/**
* RIBBON_DELETE_MESSAGE: commandlet
* Delete message from all directories.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DELETE_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(args);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
} else {
if (matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) == null)) {
Procedures.PROC_DELETE_MESSAGE(matchedEntry);
BROADCAST_TAIL = "RIBBON_UCTL_DELETE_INDEX:" + matchedEntry.INDEX;
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
}
});
/**
* RIBBON_ADD_MESSAGE_PROPERTY: commandlet
* Add custom property to message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_ADD_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty newProp = new MessageClasses.MessageProperty(parsedArgs[1], CURR_SESSION.USER_NAME, parsedArgs[2], RibbonServer.getCurrentDate());
newProp.TYPE = parsedArgs[1];
newProp.TEXT_MESSAGE = parsedArgs[2];
newProp.DATE = RibbonServer.getCurrentDate();
newProp.USER = CURR_SESSION.USER_NAME;
matchedEntry.PROPERTIES.add(newProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_DEL_MESSAGE_PROPERTY: commandlet
* Del custom property from specified message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DEL_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty findedProp = null;
java.util.ListIterator<MessageClasses.MessageProperty> propIter = matchedEntry.PROPERTIES.listIterator();
while (propIter.hasNext()) {
MessageClasses.MessageProperty currProp = propIter.next();
if (currProp.TYPE.equals(parsedArgs[1]) && currProp.DATE.equals(parsedArgs[2])) {
findedProp = currProp;
break;
}
}
if (findedProp != null) {
matchedEntry.PROPERTIES.remove(findedProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Системної ознаки не існує!";
}
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_GET_USERS: commandlet
* Get all system users without ADM group members.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_USERS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return AccessHandler.PROC_GET_USERS_UNI(false);
}
});
/** SERVER CONTROL PROTOCOL STACK [LEVEL_2 SUPPORT] **/
}
/**
* Process input from session socket and return answer;
* @param input input line from client
* @return answer form protocol to client
* @since RibbonServer a1
*/
public String process(String input) {
String[] parsed = Generic.CsvFormat.parseDoubleStruct(input);
return this.launchCommand(parsed[0], parsed[1]);
}
/**
* Launch command execution
* @param command command word
* @param args command's arguments
* @return return form commandlet object
* @since RibbonServer a1
*/
private String launchCommand(String command, String args) {
CommandLet exComm = null;
java.util.ListIterator<CommandLet> commIter = this.RIBBON_COMMANDS.listIterator();
while (commIter.hasNext()) {
CommandLet currComm = commIter.next();
if (currComm.COMMAND_NAME.equals(command)) {
if (currComm.COMM_TYPE == this.CURR_TYPE || (currComm.COMM_TYPE == CONNECTION_TYPES.ANY && this.CURR_TYPE != CONNECTION_TYPES.NULL) || this.CURR_TYPE == CONNECTION_TYPES.CONTROL) {
if (this.CURR_SESSION.USER_NAME == null && (currComm.COMM_TYPE == CONNECTION_TYPES.CLIENT || currComm.COMM_TYPE == CONNECTION_TYPES.CONTROL)) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
exComm = currComm;
}
break;
} else {
return "RIBBON_ERROR:Ця команда не може бути використана цим з’єднанням!";
}
}
}
if (exComm != null) {
try {
return exComm.exec(args);
} catch (Exception ex) {
if (RibbonServer.DEBUG_POST_EXCEPTIONS) {
StringBuffer exMesgBuf = new StringBuffer();
exMesgBuf.append("Помилка при роботі сесії ").append(this.CURR_SESSION.SESSION_TIP).append("(").append(RibbonServer.getCurrentDate()).append(")\n\n");
exMesgBuf.append("Команда:" + command + ":" + args + "\n\n");
exMesgBuf.append(ex.getClass().getName() + "\n");
StackTraceElement[] stackTrace = ex.getStackTrace();
for (StackTraceElement element : stackTrace) {
exMesgBuf.append(element.toString() + "\n");
}
MessageClasses.Message exMessage = new MessageClasses.Message(
"Звіт про помилку", "root", "UA", new String[] {RibbonServer.DEBUG_POST_DIR},
new String[] {"ІТУ", "ПОМИЛКИ"}, exMesgBuf.toString());
Procedures.PROC_POST_MESSAGE(exMessage);
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + exMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
RibbonServer.logAppend(LOG_ID, 1, "помилка при виконанні команди " + exComm.COMMAND_NAME + "!");
return "RIBBON_ERROR: помилка команди:" + ex.toString();
}
} else {
return "RIBBON_ERROR:Невідома команда!";
}
}
}
| true | true | private void InitProtocol() {
/** CONNECTION CONTROL COMMANDS [LEVEL_0 SUPPORT] **/
/**
* RIBBON_NCTL_INIT: commandlet
* Client and others application send this command to register
* this connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_INIT", CONNECTION_TYPES.NULL) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
if (CURR_TYPE == CONNECTION_TYPES.NULL) {
if (parsedArgs[1].equals(STR_VERSION)) {
try {
if (parsedArgs[0].equals("ANY") || parsedArgs[0].equals("NULL")) {
throw new IllegalArgumentException();
}
CURR_TYPE = CONNECTION_TYPES.valueOf(parsedArgs[0]);
if (!parsedArgs[2].equals(System.getProperty("file.encoding"))) {
RibbonServer.logAppend(LOG_ID, 2, "мережева сесія вимогає іншої кодової сторінки:" + parsedArgs[2]);
CURR_SESSION.setReaderEncoding(parsedArgs[2]);
}
return "OK:\nRIBBON_GCTL_FORCE_LOGIN:";
} catch (IllegalArgumentException ex) {
return "RIBBON_ERROR:Невідомий тип з'єднання!";
}
} else {
return "RIBBON_ERROR:Невідомий ідентефікатор протокола.";
}
} else {
return "RIBBON_WARNING:З'єднання вже ініціьовано!";
}
}
});
/**
* RIBBON_NCTL_LOGIN: commandlet
* Client and other applications send this command to login user.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (!RibbonServer.ACCESS_ALLOW_MULTIPLIE_LOGIN && SessionManager.isAlreadyLogined(parsedArgs[0])) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " вже увійшов до системи!\nRIBBON_GCTL_FORCE_LOGIN:";
}
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " увійшов до системи.");
if (RibbonServer.CONTROL_IS_PRESENT == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "ініційовано контроль системи!");
RibbonServer.CONTROL_IS_PRESENT = true;
}
}
CURR_SESSION.USER_NAME = parsedArgs[0];
if (RibbonServer.ACCESS_ALLOW_SESSIONS) {
CURR_SESSION.CURR_ENTRY = SessionManager.createSessionEntry(parsedArgs[0]);
CURR_SESSION.setSessionName();
return "OK:" + CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
} else {
return "OK:";
}
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_ID: commandlet
* Find out session ID.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_ID", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
} else if (CURR_SESSION.CURR_ENTRY == null) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
return CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
}
}
});
/**
* RIBBON_NCTL_RESUME: commandlet
* Resume session by given hash id.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_RESUME", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
}
SessionManager.SessionEntry exicted = SessionManager.getUserBySessionEntry(args);
if (exicted == null) {
return "RIBBON_GCTL_FORCE_LOGIN:";
} else {
String returned = AccessHandler.PROC_RESUME_USER(exicted);
if (returned == null) {
SessionManager.reniewEntry(exicted);
CURR_SESSION.USER_NAME = exicted.SESSION_USER_NAME;
CURR_SESSION.CURR_ENTRY = exicted;
CURR_SESSION.setSessionName();
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
}
});
/**
* RIBBON_NCTL_REM_LOGIN: commandlet
* Remote login command.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_REM_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_REMOTE && !IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " видалено увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " видалено увійшов до системи.");
}
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_USERNAME: commandlet
* Get current session username.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_USERNAME", CONNECTION_TYPES.ANY) {
public String exec(String args) {
if (CURR_SESSION.USER_NAME != null) {
return "OK:" + CURR_SESSION.USER_NAME;
} else {
return "RIBBON_ERROR:Вхід до системи не виконано!";
}
}
});
/**
* RIBBON_NCTL_SET_REMOTE_MODE: commandlet
* Set remote flag of this session.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_SET_REMOTE_MODE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!RibbonServer.ACCESS_ALLOW_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (!AccessHandler.isUserIsMemberOf(CURR_SESSION.USER_NAME, RibbonServer.ACCESS_REMOTE_GROUP)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
IS_REMOTE = "1".equals(args) ? true : false;
if (IS_REMOTE) {
RibbonServer.logAppend(LOG_ID, 3, "увімкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
} else {
RibbonServer.logAppend(LOG_ID, 3, "вимкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
}
return "OK:" + (IS_REMOTE ? "1" : "0");
}
});
/**
* RIBBON_NCTL_ACCESS_CONTEXT: commandlet
* Change access mode of next command.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to process() method directly!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_ACCESS_CONTEXT", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!RibbonServer.ACCESS_ALLOW_REMOTE && !IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
UserClasses.UserEntry overUser = AccessHandler.getEntryByName(Generic.CsvFormat.commonParseLine(args, 1)[0]);
if (overUser == null) {
return "RIBBON_ERROR:Користувача не знайдено!";
} else if (!overUser.IS_ENABLED) {
return "RIBBON_ERROR:Користувача заблоковано!";
}
String oldUserName = CURR_SESSION.USER_NAME;
CURR_SESSION.USER_NAME = overUser.USER_NAME;
CURR_SESSION.outStream.println("PROCEED:");
String subResult = null;
try {
subResult = process(CURR_SESSION.inStream.readLine());
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "неможливо прочитати дані з сокету!");
SessionManager.closeSession(CURR_SESSION);
}
CURR_SESSION.USER_NAME = oldUserName;
return subResult;
}
});
/**
* RIBBON_NCTL_CLOSE: commandlet
* Exit command to close connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_CLOSE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && SessionManager.hasOtherControl(CURR_SESSION) == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "контроль над системою завершено!");
RibbonServer.CONTROL_IS_PRESENT = false;
}
return "COMMIT_CLOSE:";
}
});
/** GENERAL PROTOCOL STACK [LEVEL_1 SUPPORT] **/
/**
* RIBBON_GET_DIRS: commandlet
* Return all dirs to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_DIRS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Directories.PROC_GET_DIRS();
}
});
/**
* RIBBON_GET_PSEUDO: commandlet
* Return csv list of pseudo directories which user may use.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
return Directories.PROC_GET_PSEUDO(CURR_SESSION.USER_NAME);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_TAGS: commandlet
* Return all tags to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_TAGS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_GET_TAGS();
}
});
/**
* RIBBON_LOAD_BASE_FROM_INDEX: commandlet
* Return all messages which were released later than specified index.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_LOAD_BASE_FROM_INDEX", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_LOAD_BASE_FROM_INDEX(args);
}
});
/**
* RIBBON_POST_MESSAGE: commandlet
* Post message to the system.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.Message recievedMessage = new MessageClasses.Message();
recievedMessage.createMessageForPost(args);
recievedMessage.AUTHOR = CURR_SESSION.USER_NAME;
Boolean collectMessage = true;
StringBuffer messageBuffer = new StringBuffer();
String inLine;
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
recievedMessage.CONTENT = messageBuffer.toString();
String answer = Procedures.PROC_POST_MESSAGE(recievedMessage);
if (answer.equals("OK:")) {
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + recievedMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
return answer;
}
});
/**
* RIBBON_POST_MESSAGE_BY_PSEUDO: commandlet
* Post message from remote interface to the system by using pseudo directory.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to RIBBON_POST_MESSAGE commandlet
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE_BY_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
java.util.ArrayList<String[]> parsed = Generic.CsvFormat.complexParseLine(args, 4, 1);
Directories.PseudoDirEntry currPostPseudo = Directories.getPseudoDir(parsed.get(0)[0]);
if (currPostPseudo == null) {
return "RIBBON_ERROR:Псевдонапрямок " + parsed.get(0)[0] + " не існує.";
}
String[] postDirs = currPostPseudo.getinternalDirectories();
String commandToPost = "RIBBON_POST_MESSAGE:-1," + args.replace("{" + currPostPseudo.PSEUDO_DIR_NAME + "}", Generic.CsvFormat.renderGroup(postDirs));
RibbonServer.logAppend(LOG_ID, 3, "додано повідомлення через псевдонапрямок '" + currPostPseudo.PSEUDO_DIR_NAME + "'");
return process(commandToPost);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_MESSAGE: commandlet
* Retrieve message body.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
String givenDir = parsedArgs[0];
String givenIndex = parsedArgs[1];
StringBuffer returnedMessage = new StringBuffer();
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, givenDir, 0) == false) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + givenDir;
}
String dirPath = Directories.getDirPath(givenDir);
if (dirPath == null) {
return "RIBBON_ERROR:Напрямок " + givenDir + " не існує!";
} else {
try {
java.io.BufferedReader messageReader = new java.io.BufferedReader(new java.io.FileReader(dirPath + givenIndex));
while (messageReader.ready()) {
returnedMessage.append(messageReader.readLine());
returnedMessage.append("\n");
}
return returnedMessage.append("END:").toString();
} catch (java.io.FileNotFoundException ex) {
return "RIBBON_ERROR:Повідмолення не існує!";
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "помилка зчитування повідомлення " + givenDir + ":" + givenIndex);
return "RIBBON_ERROR:Помилка виконання команди!";
}
}
}
});
/**
* RIBBON_MODIFY_MESSAGE: commandlet
* Modify text of existing message.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_MODIFY_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
StringBuffer messageBuffer = new StringBuffer();
String inLine;
Boolean collectMessage = true;
String[] parsedArgs = Generic.CsvFormat.splitCsv(args);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
MessageClasses.Message modTemplate = new MessageClasses.Message();
modTemplate.createMessageForModify(parsedArgs[1]);
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
modTemplate.CONTENT = messageBuffer.toString();
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
Integer oldIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2);
Integer newIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, modTemplate.DIRS, 1);
if ((CURR_SESSION.USER_NAME.equals(matchedEntry.AUTHOR) && (newIntFlag == null)) || ((oldIntFlag == null) && (newIntFlag == null))) {
for (Integer dirIndex = 0; dirIndex < matchedEntry.DIRS.length; dirIndex++) {
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, matchedEntry.DIRS[dirIndex], 1) == true) {
continue;
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[dirIndex] + ".";
}
}
Procedures.PROC_MODIFY_MESSAGE(matchedEntry, modTemplate);
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
if (oldIntFlag != null) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[oldIntFlag] + ".";
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + modTemplate.DIRS[newIntFlag] + ".";
}
}
}
});
/**
* RIBBON_DELETE_MESSAGE: commandlet
* Delete message from all directories.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DELETE_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(args);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
} else {
if (matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) == null)) {
Procedures.PROC_DELETE_MESSAGE(matchedEntry);
BROADCAST_TAIL = "RIBBON_UCTL_DELETE_INDEX:" + matchedEntry.INDEX;
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
}
});
/**
* RIBBON_ADD_MESSAGE_PROPERTY: commandlet
* Add custom property to message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_ADD_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty newProp = new MessageClasses.MessageProperty(parsedArgs[1], CURR_SESSION.USER_NAME, parsedArgs[2], RibbonServer.getCurrentDate());
newProp.TYPE = parsedArgs[1];
newProp.TEXT_MESSAGE = parsedArgs[2];
newProp.DATE = RibbonServer.getCurrentDate();
newProp.USER = CURR_SESSION.USER_NAME;
matchedEntry.PROPERTIES.add(newProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_DEL_MESSAGE_PROPERTY: commandlet
* Del custom property from specified message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DEL_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty findedProp = null;
java.util.ListIterator<MessageClasses.MessageProperty> propIter = matchedEntry.PROPERTIES.listIterator();
while (propIter.hasNext()) {
MessageClasses.MessageProperty currProp = propIter.next();
if (currProp.TYPE.equals(parsedArgs[1]) && currProp.DATE.equals(parsedArgs[2])) {
findedProp = currProp;
break;
}
}
if (findedProp != null) {
matchedEntry.PROPERTIES.remove(findedProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Системної ознаки не існує!";
}
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_GET_USERS: commandlet
* Get all system users without ADM group members.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_USERS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return AccessHandler.PROC_GET_USERS_UNI(false);
}
});
/** SERVER CONTROL PROTOCOL STACK [LEVEL_2 SUPPORT] **/
}
| private void InitProtocol() {
/** CONNECTION CONTROL COMMANDS [LEVEL_0 SUPPORT] **/
/**
* RIBBON_NCTL_INIT: commandlet
* Client and others application send this command to register
* this connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_INIT", CONNECTION_TYPES.NULL) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
if (CURR_TYPE == CONNECTION_TYPES.NULL) {
if (parsedArgs[1].equals(STR_VERSION)) {
try {
if (parsedArgs[0].equals("ANY") || parsedArgs[0].equals("NULL")) {
throw new IllegalArgumentException();
}
CURR_TYPE = CONNECTION_TYPES.valueOf(parsedArgs[0]);
if (!parsedArgs[2].equals(System.getProperty("file.encoding"))) {
RibbonServer.logAppend(LOG_ID, 2, "мережева сесія вимогає іншої кодової сторінки:" + parsedArgs[2]);
CURR_SESSION.setReaderEncoding(parsedArgs[2]);
}
return "OK:\nRIBBON_GCTL_FORCE_LOGIN:";
} catch (IllegalArgumentException ex) {
return "RIBBON_ERROR:Невідомий тип з'єднання!";
}
} else {
return "RIBBON_ERROR:Невідомий ідентефікатор протокола.";
}
} else {
return "RIBBON_WARNING:З'єднання вже ініціьовано!";
}
}
});
/**
* RIBBON_NCTL_LOGIN: commandlet
* Client and other applications send this command to login user.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (!RibbonServer.ACCESS_ALLOW_MULTIPLIE_LOGIN && SessionManager.isAlreadyLogined(parsedArgs[0])) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " вже увійшов до системи!\nRIBBON_GCTL_FORCE_LOGIN:";
}
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " увійшов до системи.");
if (RibbonServer.CONTROL_IS_PRESENT == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "ініційовано контроль системи!");
RibbonServer.CONTROL_IS_PRESENT = true;
}
}
CURR_SESSION.USER_NAME = parsedArgs[0];
if (RibbonServer.ACCESS_ALLOW_SESSIONS) {
CURR_SESSION.CURR_ENTRY = SessionManager.createSessionEntry(parsedArgs[0]);
CURR_SESSION.setSessionName();
return "OK:" + CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
} else {
return "OK:";
}
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_ID: commandlet
* Find out session ID.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_ID", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
} else if (CURR_SESSION.CURR_ENTRY == null) {
return "RIBBON_ERROR:Вхід не виконано!\nRIBBON_GCTL_FORCE_LOGIN:";
} else {
return CURR_SESSION.CURR_ENTRY.SESSION_HASH_ID;
}
}
});
/**
* RIBBON_NCTL_RESUME: commandlet
* Resume session by given hash id.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_RESUME", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_SESSIONS) {
return "RIBBON_ERROR:Сесії вимкнено!\nRIBBON_GCTL_FORCE_LOGIN:";
}
SessionManager.SessionEntry exicted = SessionManager.getUserBySessionEntry(args);
if (exicted == null) {
return "RIBBON_GCTL_FORCE_LOGIN:";
} else {
String returned = AccessHandler.PROC_RESUME_USER(exicted);
if (returned == null) {
SessionManager.reniewEntry(exicted);
CURR_SESSION.USER_NAME = exicted.SESSION_USER_NAME;
CURR_SESSION.CURR_ENTRY = exicted;
CURR_SESSION.setSessionName();
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
}
});
/**
* RIBBON_NCTL_REM_LOGIN: commandlet
* Remote login command.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_REM_LOGIN", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (!RibbonServer.ACCESS_ALLOW_REMOTE && !IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 2);
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && (!AccessHandler.isUserIsMemberOf(parsedArgs[0], "ADM"))) {
return "RIBBON_ERROR:Користувач " + parsedArgs[0] + " не є адміністратором системи.\nRIBBON_GCTL_FORCE_LOGIN:";
}
String returned = AccessHandler.PROC_LOGIN_USER(parsedArgs[0], parsedArgs[1]);
if (returned == null) {
if (CURR_TYPE == CONNECTION_TYPES.CLIENT) {
RibbonServer.logAppend(LOG_ID, 3, "користувач " + parsedArgs[0] + " видалено увійшов до системи.");
} else if (CURR_TYPE == CONNECTION_TYPES.CONTROL) {
RibbonServer.logAppend(LOG_ID, 3, "адміністратор " + parsedArgs[0] + " видалено увійшов до системи.");
}
return "OK:";
} else {
return "RIBBON_ERROR:" + returned + "\nRIBBON_GCTL_FORCE_LOGIN:";
}
}
});
/**
* RIBBON_NCTL_GET_USERNAME: commandlet
* Get current session username.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_GET_USERNAME", CONNECTION_TYPES.ANY) {
public String exec(String args) {
if (CURR_SESSION.USER_NAME != null) {
return "OK:" + CURR_SESSION.USER_NAME;
} else {
return "RIBBON_ERROR:Вхід до системи не виконано!";
}
}
});
/**
* RIBBON_NCTL_SET_REMOTE_MODE: commandlet
* Set remote flag of this session.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_SET_REMOTE_MODE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!RibbonServer.ACCESS_ALLOW_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
} else if (!AccessHandler.isUserIsMemberOf(CURR_SESSION.USER_NAME, RibbonServer.ACCESS_REMOTE_GROUP)) {
return "RIBBON_ERROR:Ця сессія не може використовувати видалений режим!";
}
IS_REMOTE = "1".equals(args) ? true : false;
if (IS_REMOTE) {
RibbonServer.logAppend(LOG_ID, 3, "увімкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
} else {
RibbonServer.logAppend(LOG_ID, 3, "вимкнено видалений режим (" + CURR_SESSION.SESSION_TIP + ")");
}
return "OK:" + (IS_REMOTE ? "1" : "0");
}
});
/**
* RIBBON_NCTL_ACCESS_CONTEXT: commandlet
* Change access mode of next command.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to process() method directly!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_ACCESS_CONTEXT", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
} else if (!IS_REMOTE) {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
UserClasses.UserEntry overUser = AccessHandler.getEntryByName(Generic.CsvFormat.commonParseLine(args, 1)[0]);
if (overUser == null) {
return "RIBBON_ERROR:Користувача не знайдено!";
} else if (!overUser.IS_ENABLED) {
return "RIBBON_ERROR:Користувача заблоковано!";
}
String oldUserName = CURR_SESSION.USER_NAME;
CURR_SESSION.USER_NAME = overUser.USER_NAME;
CURR_SESSION.outStream.println("PROCEED:");
String subResult = null;
try {
subResult = process(CURR_SESSION.inStream.readLine());
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "неможливо прочитати дані з сокету!");
SessionManager.closeSession(CURR_SESSION);
}
CURR_SESSION.USER_NAME = oldUserName;
return subResult;
}
});
/**
* RIBBON_NCTL_CLOSE: commandlet
* Exit command to close connection.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_NCTL_CLOSE", CONNECTION_TYPES.ANY) {
@Override
public String exec(String args) {
if (CURR_TYPE == CONNECTION_TYPES.CONTROL && SessionManager.hasOtherControl(CURR_SESSION) == false) {
RibbonServer.logAppend(RibbonServer.LOG_ID, 2, "контроль над системою завершено!");
RibbonServer.CONTROL_IS_PRESENT = false;
}
return "COMMIT_CLOSE:";
}
});
/** GENERAL PROTOCOL STACK [LEVEL_1 SUPPORT] **/
/**
* RIBBON_GET_DIRS: commandlet
* Return all dirs to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_DIRS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Directories.PROC_GET_DIRS();
}
});
/**
* RIBBON_GET_PSEUDO: commandlet
* Return csv list of pseudo directories which user may use.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
if (CURR_SESSION.USER_NAME == null) {
return "RIBBON_ERROR:Вхід не виконано!";
}
return Directories.PROC_GET_PSEUDO(CURR_SESSION.USER_NAME);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_TAGS: commandlet
* Return all tags to client in csv form.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_TAGS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_GET_TAGS();
}
});
/**
* RIBBON_LOAD_BASE_FROM_INDEX: commandlet
* Return all messages which were released later than specified index.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_LOAD_BASE_FROM_INDEX", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return Messenger.PROC_LOAD_BASE_FROM_INDEX(args);
}
});
/**
* RIBBON_POST_MESSAGE: commandlet
* Post message to the system.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.Message recievedMessage = new MessageClasses.Message();
recievedMessage.createMessageForPost(args);
recievedMessage.AUTHOR = CURR_SESSION.USER_NAME;
Boolean collectMessage = true;
StringBuffer messageBuffer = new StringBuffer();
String inLine;
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
recievedMessage.CONTENT = messageBuffer.toString();
String answer = Procedures.PROC_POST_MESSAGE(recievedMessage);
if (answer.equals("OK:")) {
BROADCAST_TAIL = "RIBBON_UCTL_LOAD_INDEX:" + recievedMessage.returnEntry().toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
}
return answer;
}
});
/**
* RIBBON_POST_MESSAGE_BY_PSEUDO: commandlet
* Post message from remote interface to the system by using pseudo directory.
* WARNING! this commandlet grab socket control!
* WARNING! this commandlet calls to RIBBON_POST_MESSAGE commandlet
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_POST_MESSAGE_BY_PSEUDO", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
if (IS_REMOTE) {
java.util.ArrayList<String[]> parsed = Generic.CsvFormat.complexParseLine(args, 4, 1);
Directories.PseudoDirEntry currPostPseudo = Directories.getPseudoDir(parsed.get(0)[0]);
if (currPostPseudo == null) {
return "RIBBON_ERROR:Псевдонапрямок " + parsed.get(0)[0] + " не існує.";
}
String[] postDirs = currPostPseudo.getinternalDirectories();
String commandToPost = "RIBBON_POST_MESSAGE:-1," + args.replace("{" + currPostPseudo.PSEUDO_DIR_NAME + "}", Generic.CsvFormat.renderGroup(postDirs));
RibbonServer.logAppend(LOG_ID, 3, "додано повідомлення через псевдонапрямок '" + currPostPseudo.PSEUDO_DIR_NAME + "'");
return process(commandToPost);
} else {
return "RIBBON_ERROR:Видалений режим вимкнено!";
}
}
});
/**
* RIBBON_GET_MESSAGE: commandlet
* Retrieve message body.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = args.split(",");
String givenDir = parsedArgs[0];
String givenIndex = parsedArgs[1];
StringBuffer returnedMessage = new StringBuffer();
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, givenDir, 0) == false) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + givenDir;
}
String dirPath = Directories.getDirPath(givenDir);
if (dirPath == null) {
return "RIBBON_ERROR:Напрямок " + givenDir + " не існує!";
} else {
try {
java.io.BufferedReader messageReader = new java.io.BufferedReader(new java.io.FileReader(dirPath + givenIndex));
while (messageReader.ready()) {
returnedMessage.append(messageReader.readLine());
returnedMessage.append("\n");
}
return returnedMessage.append("END:").toString();
} catch (java.io.FileNotFoundException ex) {
return "RIBBON_ERROR:Повідмолення не існує!";
} catch (java.io.IOException ex) {
RibbonServer.logAppend(LOG_ID, 1, "помилка зчитування повідомлення " + givenDir + ":" + givenIndex);
return "RIBBON_ERROR:Помилка виконання команди!";
}
}
}
});
/**
* RIBBON_MODIFY_MESSAGE: commandlet
* Modify text of existing message.
* WARNING! this commandlet grab socket control!
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_MODIFY_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
StringBuffer messageBuffer = new StringBuffer();
String inLine;
Boolean collectMessage = true;
String[] parsedArgs = Generic.CsvFormat.splitCsv(args);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
MessageClasses.Message modTemplate = new MessageClasses.Message();
modTemplate.createMessageForModify(parsedArgs[1]);
while (collectMessage) {
try {
inLine = CURR_SESSION.inStream.readLine();
if (!inLine.equals("END:")) {
messageBuffer.append(inLine);
messageBuffer.append("\n");
} else {
collectMessage = false;
}
} catch (java.io.IOException ex) {
return "RIBBON_ERROR:Неможливо прочитати повідомлення з сокету!";
}
}
modTemplate.CONTENT = messageBuffer.toString();
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
Integer oldIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2);
Integer newIntFlag = AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, modTemplate.DIRS, 1);
if ((CURR_SESSION.USER_NAME.equals(matchedEntry.AUTHOR) && (newIntFlag == null)) || ((oldIntFlag == null) && (newIntFlag == null))) {
for (Integer dirIndex = 0; dirIndex < matchedEntry.DIRS.length; dirIndex++) {
if (AccessHandler.checkAccess(CURR_SESSION.USER_NAME, matchedEntry.DIRS[dirIndex], 1) == true) {
continue;
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[dirIndex] + ".";
}
}
Procedures.PROC_MODIFY_MESSAGE(matchedEntry, modTemplate);
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
if (oldIntFlag != null) {
return "RIBBON_ERROR:Помилка доступу до напрямку " + matchedEntry.DIRS[oldIntFlag] + ".";
} else {
return "RIBBON_ERROR:Помилка доступу до напрямку " + modTemplate.DIRS[newIntFlag] + ".";
}
}
}
});
/**
* RIBBON_DELETE_MESSAGE: commandlet
* Delete message from all directories.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DELETE_MESSAGE", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(args);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
} else {
if (matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) == null)) {
Procedures.PROC_DELETE_MESSAGE(matchedEntry);
BROADCAST_TAIL = "RIBBON_UCTL_DELETE_INDEX:" + matchedEntry.INDEX;
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
}
});
/**
* RIBBON_ADD_MESSAGE_PROPERTY: commandlet
* Add custom property to message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_ADD_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty newProp = new MessageClasses.MessageProperty(parsedArgs[1], CURR_SESSION.USER_NAME, parsedArgs[2], RibbonServer.getCurrentDate());
newProp.TYPE = parsedArgs[1];
newProp.TEXT_MESSAGE = parsedArgs[2];
newProp.DATE = RibbonServer.getCurrentDate();
newProp.USER = CURR_SESSION.USER_NAME;
matchedEntry.PROPERTIES.add(newProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_DEL_MESSAGE_PROPERTY: commandlet
* Del custom property from specified message.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_DEL_MESSAGE_PROPERTY", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
String[] parsedArgs = Generic.CsvFormat.commonParseLine(args, 3);
MessageClasses.MessageEntry matchedEntry = Messenger.getMessageEntryByIndex(parsedArgs[0]);
if (matchedEntry == null) {
return "RIBBON_ERROR:Повідмолення не існує!";
}
if ((matchedEntry.AUTHOR.equals(CURR_SESSION.USER_NAME) || (AccessHandler.checkAccessForAll(CURR_SESSION.USER_NAME, matchedEntry.DIRS, 2) != null))) {
MessageClasses.MessageProperty findedProp = null;
java.util.ListIterator<MessageClasses.MessageProperty> propIter = matchedEntry.PROPERTIES.listIterator();
while (propIter.hasNext()) {
MessageClasses.MessageProperty currProp = propIter.next();
if (currProp.TYPE.equals(parsedArgs[1]) && currProp.DATE.equals(parsedArgs[2])) {
findedProp = currProp;
break;
}
}
if (findedProp != null) {
matchedEntry.PROPERTIES.remove(findedProp);
IndexReader.updateBaseIndex();
BROADCAST_TAIL = "RIBBON_UCTL_UPDATE_INDEX:" + matchedEntry.toCsv();
BROADCAST_TYPE = CONNECTION_TYPES.CLIENT;
return "OK:";
} else {
return "RIBBON_ERROR:Системної ознаки не існує!";
}
} else {
return "RIBBON_ERROR:Помилка доступу до повідомлення.";
}
}
});
/**
* RIBBON_GET_USERS: commandlet
* Get all system users without ADM group members.
*/
this.RIBBON_COMMANDS.add(new CommandLet("RIBBON_GET_USERS", CONNECTION_TYPES.CLIENT) {
@Override
public String exec(String args) {
return AccessHandler.PROC_GET_USERS_UNI(false);
}
});
/** SERVER CONTROL PROTOCOL STACK [LEVEL_2 SUPPORT] **/
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java
index fc63f0e6d..869aeb0e9 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/administrative/mapper/SearchItemForm.java
@@ -1,194 +1,203 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.administrative.mapper;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.handle.HandleManager;
import org.dspace.search.DSQuery;
import org.dspace.search.QueryArgs;
import org.dspace.search.QueryResults;
import org.xml.sax.SAXException;
/**
* Search for items from other collections to map into this collection.
*
* @author Scott phillips
*/
public class SearchItemForm extends AbstractDSpaceTransformer {
/** Language strings */
private static final Message T_dspace_home = message("xmlui.general.dspace_home");
private static final Message T_submit_cancel = message("xmlui.general.cancel");
private static final Message T_mapper_trail = message("xmlui.administrative.mapper.general.mapper_trail");
private static final Message T_title = message("xmlui.administrative.mapper.SearchItemForm.title");
private static final Message T_trail = message("xmlui.administrative.mapper.SearchItemForm.trail");
private static final Message T_head1 = message("xmlui.administrative.mapper.SearchItemForm.head1");
private static final Message T_submit_map = message("xmlui.administrative.mapper.SearchItemForm.submit_map");
private static final Message T_column1 = message("xmlui.administrative.mapper.SearchItemForm.column1");
private static final Message T_column2 = message("xmlui.administrative.mapper.SearchItemForm.column2");
private static final Message T_column3 = message("xmlui.administrative.mapper.SearchItemForm.column3");
private static final Message T_column4 = message("xmlui.administrative.mapper.SearchItemForm.column4");
public void addPageMeta(PageMeta pageMeta) throws WingException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/", T_dspace_home);
pageMeta.addTrail().addContent(T_mapper_trail);
pageMeta.addTrail().addContent(T_trail);
}
public void addBody(Body body) throws SAXException, WingException, SQLException, IOException
{
// Get our parameters and state;
int collectionID = parameters.getParameterAsInteger("collectionID",-1);
Collection collection = Collection.find(context,collectionID);
String query = decodeFromURL(parameters.getParameter("query",null));
java.util.List<Item> items = preformSearch(collection,query);
// DIVISION: manage-mapper
Division div = body.addInteractiveDivision("search-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper");
div.setHead(T_head1.parameterize(query));
Para actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
Table table = div.addTable("search-items-table",1,1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column1);
header.addCellContent(T_column2);
header.addCellContent(T_column3);
header.addCellContent(T_column4);
for (Item item : items)
{
String itemID = String.valueOf(item.getID());
Collection owningCollection = item.getOwningCollection();
- String owning = owningCollection.getMetadata("name");
- String author = "unkown";
- DCValue[] dcAuthors = item.getDC("contributor",Item.ANY,Item.ANY);
- if (dcAuthors != null && dcAuthors.length >= 1)
+ String owning = "unknown";
+ if (owningCollection != null)
+ owning = owningCollection.getMetadata("name");
+ String author = "unknown";
+ DCValue[] dcCreators = item.getDC("creator",Item.ANY,Item.ANY);
+ if (dcCreators != null && dcCreators.length >= 1)
{
- author = dcAuthors[0].value;
- }
+ author = dcCreators[0].value;
+ } else {
+ // Do a fall back look for contributors
+ DCValue[] dcContributors = item.getDC("contributor",Item.ANY,Item.ANY);
+ if (dcContributors != null && dcContributors.length >= 1)
+ {
+ author = dcContributors[0].value;
+ }
+ }
String title = "untitled";
DCValue[] dcTitles = item.getDC("title",null,Item.ANY);
if (dcTitles != null && dcTitles.length >= 1)
{
title = dcTitles[0].value;
}
String url = contextPath+"/handle/"+item.getHandle();
Row row = table.addRow();
boolean canBeMapped = true;
Collection[] collections = item.getCollections();
for (Collection c : collections)
{
if (c.getID() == collectionID)
{
canBeMapped = false;
}
}
if (canBeMapped)
{
CheckBox select = row.addCell().addCheckBox("itemID");
select.setLabel("Select");
select.addOption(itemID);
}
else
{
row.addCell().addContent("");
}
row.addCellContent(owning);
row.addCell().addXref(url,author);
row.addCell().addXref(url,title);
}
actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("administrative-continue").setValue(knot.getId());
}
/**
* Search the repository for items in other collections that can be mapped into this one.
*
* @param collection The collection to mapp into
* @param query The search query.
*/
private java.util.List<Item> preformSearch(Collection collection, String query) throws SQLException, IOException
{
// Search the repository
QueryArgs queryArgs = new QueryArgs();
queryArgs.setQuery(query);
queryArgs.setPageSize(Integer.MAX_VALUE);
QueryResults results = DSQuery.doQuery(context, queryArgs);
// Get a list of found items
ArrayList<Item> items = new ArrayList<Item>();
@SuppressWarnings("unchecked")
java.util.List<String> handles = results.getHitHandles();
for (String handle : handles)
{
DSpaceObject resultDSO = HandleManager.resolveToObject(context, handle);
if (resultDSO instanceof Item)
{
Item item = (Item) resultDSO;
if (!item.isOwningCollection(collection))
{
items.add(item);
}
}
}
return items;
}
}
| false | true | public void addBody(Body body) throws SAXException, WingException, SQLException, IOException
{
// Get our parameters and state;
int collectionID = parameters.getParameterAsInteger("collectionID",-1);
Collection collection = Collection.find(context,collectionID);
String query = decodeFromURL(parameters.getParameter("query",null));
java.util.List<Item> items = preformSearch(collection,query);
// DIVISION: manage-mapper
Division div = body.addInteractiveDivision("search-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper");
div.setHead(T_head1.parameterize(query));
Para actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
Table table = div.addTable("search-items-table",1,1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column1);
header.addCellContent(T_column2);
header.addCellContent(T_column3);
header.addCellContent(T_column4);
for (Item item : items)
{
String itemID = String.valueOf(item.getID());
Collection owningCollection = item.getOwningCollection();
String owning = owningCollection.getMetadata("name");
String author = "unkown";
DCValue[] dcAuthors = item.getDC("contributor",Item.ANY,Item.ANY);
if (dcAuthors != null && dcAuthors.length >= 1)
{
author = dcAuthors[0].value;
}
String title = "untitled";
DCValue[] dcTitles = item.getDC("title",null,Item.ANY);
if (dcTitles != null && dcTitles.length >= 1)
{
title = dcTitles[0].value;
}
String url = contextPath+"/handle/"+item.getHandle();
Row row = table.addRow();
boolean canBeMapped = true;
Collection[] collections = item.getCollections();
for (Collection c : collections)
{
if (c.getID() == collectionID)
{
canBeMapped = false;
}
}
if (canBeMapped)
{
CheckBox select = row.addCell().addCheckBox("itemID");
select.setLabel("Select");
select.addOption(itemID);
}
else
{
row.addCell().addContent("");
}
row.addCellContent(owning);
row.addCell().addXref(url,author);
row.addCell().addXref(url,title);
}
actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("administrative-continue").setValue(knot.getId());
}
| public void addBody(Body body) throws SAXException, WingException, SQLException, IOException
{
// Get our parameters and state;
int collectionID = parameters.getParameterAsInteger("collectionID",-1);
Collection collection = Collection.find(context,collectionID);
String query = decodeFromURL(parameters.getParameter("query",null));
java.util.List<Item> items = preformSearch(collection,query);
// DIVISION: manage-mapper
Division div = body.addInteractiveDivision("search-items",contextPath + "/admin/mapper", Division.METHOD_GET,"primary administrative mapper");
div.setHead(T_head1.parameterize(query));
Para actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
Table table = div.addTable("search-items-table",1,1);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_column1);
header.addCellContent(T_column2);
header.addCellContent(T_column3);
header.addCellContent(T_column4);
for (Item item : items)
{
String itemID = String.valueOf(item.getID());
Collection owningCollection = item.getOwningCollection();
String owning = "unknown";
if (owningCollection != null)
owning = owningCollection.getMetadata("name");
String author = "unknown";
DCValue[] dcCreators = item.getDC("creator",Item.ANY,Item.ANY);
if (dcCreators != null && dcCreators.length >= 1)
{
author = dcCreators[0].value;
} else {
// Do a fall back look for contributors
DCValue[] dcContributors = item.getDC("contributor",Item.ANY,Item.ANY);
if (dcContributors != null && dcContributors.length >= 1)
{
author = dcContributors[0].value;
}
}
String title = "untitled";
DCValue[] dcTitles = item.getDC("title",null,Item.ANY);
if (dcTitles != null && dcTitles.length >= 1)
{
title = dcTitles[0].value;
}
String url = contextPath+"/handle/"+item.getHandle();
Row row = table.addRow();
boolean canBeMapped = true;
Collection[] collections = item.getCollections();
for (Collection c : collections)
{
if (c.getID() == collectionID)
{
canBeMapped = false;
}
}
if (canBeMapped)
{
CheckBox select = row.addCell().addCheckBox("itemID");
select.setLabel("Select");
select.addOption(itemID);
}
else
{
row.addCell().addContent("");
}
row.addCellContent(owning);
row.addCell().addXref(url,author);
row.addCell().addXref(url,title);
}
actions = div.addPara();
actions.addButton("submit_map").setValue(T_submit_map);
actions.addButton("submit_cancel").setValue(T_submit_cancel);
div.addHidden("administrative-continue").setValue(knot.getId());
}
|
diff --git a/src/main/java/eu/trentorise/smartcampus/ac/provider/services/AcProviderServiceImpl.java b/src/main/java/eu/trentorise/smartcampus/ac/provider/services/AcProviderServiceImpl.java
index 93051ad..654a779 100644
--- a/src/main/java/eu/trentorise/smartcampus/ac/provider/services/AcProviderServiceImpl.java
+++ b/src/main/java/eu/trentorise/smartcampus/ac/provider/services/AcProviderServiceImpl.java
@@ -1,235 +1,237 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.trentorise.smartcampus.ac.provider.services;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import eu.trentorise.smartcampus.ac.provider.AcProviderService;
import eu.trentorise.smartcampus.ac.provider.AcServiceException;
import eu.trentorise.smartcampus.ac.provider.model.Attribute;
import eu.trentorise.smartcampus.ac.provider.model.Authority;
import eu.trentorise.smartcampus.ac.provider.model.User;
import eu.trentorise.smartcampus.ac.provider.repository.AcDao;
/**
*
* @author Viktor Pravdin
*/
@WebService(endpointInterface = "eu.trentorise.smartcampus.ac.provider.AcProviderService")
@Service
public class AcProviderServiceImpl implements AcProviderService {
@Autowired
private AcDao dao;
@Autowired
private CreationWrapper creationWrapper;
private SecureRandom random;
@PostConstruct
private void init() {
random = new SecureRandom();
}
@Override
public User createUser(String authToken, long expDate,
List<Attribute> attributes) throws AcServiceException {
User user = new User();
user.setAuthToken(authToken);
user.setExpTime(expDate);
user.setAttributes(attributes);
try {
creationWrapper.create(user);
} catch (Exception e) {
throw new AcServiceException(e);
}
return user;
}
@Override
public boolean removeUser(String authToken) throws AcServiceException {
User user = dao.readUser(authToken);
if (user != null) {
return dao.delete(user);
}
return false;
}
@Override
public User getUserByToken(String authToken) throws AcServiceException {
return dao.readUser(authToken);
}
@Override
public List<User> getUsersByAttributes(List<Attribute> attributes)
throws AcServiceException {
return dao.readUsers(attributes);
}
/**
* Updates the user data with the given values. If a new value for an
* already existing value is not specified then the old value remains
* untouched.
*
* @param userId
* The ID of the user. Must not be null
* @param authToken
* The new authentication token or null if the token shouldn't be
* updated
* @param expTime
* The new expiration time or null if it shouldn't be updated.
* Must not be null if a new authentication token is present.
* Ignored if the auth token is null.
* @param attributes
* The map of the attributes. The existing attributes are
* updated, the new ones are added, the old ones are kept intact.
* @throws IllegalArgumentException
* if the user with the given ID doesn't exist or if the
* expiration time is not specified for an authentication token
*/
@Override
public void updateUser(long userId, String authToken, Long expTime,
List<Attribute> attributes) throws AcServiceException {
User user = dao.readUser(userId);
if (user == null) {
throw new IllegalArgumentException(
"The user with that ID doesn't exist");
}
if (authToken != null) {
if (expTime == null) {
throw new IllegalArgumentException(
"The expiration time is not specified");
}
user.setAuthToken(authToken);
+ }
+ if (expTime != null) {
user.setExpTime(expTime);
}
List<Attribute> tmp = new LinkedList<Attribute>();
for (Attribute oldA : user.getAttributes()) {
Attribute remove = null;
for (Attribute newA : tmp) {
if (oldA.getAuthority().equals(newA.getAuthority())
&& oldA.getKey().equals(newA.getKey())) {
oldA.setValue(newA.getValue());
remove = newA;
break;
}
}
if (remove != null) {
tmp.remove(remove);
}
}
user.getAttributes().addAll(tmp);
dao.update(user);
}
@Override
public boolean isValidUser(String authToken) throws AcServiceException {
long time = System.currentTimeMillis();
User user = dao.readUser(authToken);
return user != null && ((user.getExpDate() - time) > 0);
}
/**
* Fetches the user attributes that match the given authority and the key.
* If neither is given then it will return all attributes of the user, if
* the authority is given then it will return only the attributes of that
* authority and if the key is also given then it will return only the
* attributes of that authority that have the given key.
*
* @param authToken
* The authentication token of the user
* @param authority
* The authority name
* @param key
* The key of the attribute
* @return The set of attributes that match the parameters
*/
@Override
public List<Attribute> getUserAttributes(String authToken,
String authority, String key) throws AcServiceException {
User user = getUserByToken(authToken);
List<Attribute> attrs = new ArrayList<Attribute>();
if (authority != null) {
for (Attribute a : user.getAttributes()) {
if (authority.equals(a.getAuthority().getName())) {
if (key != null && !key.equals(a.getKey()))
continue;
attrs.add(a);
}
}
} else {
attrs.addAll(user.getAttributes());
}
return attrs;
}
@Override
public Collection<Authority> getAuthorities() throws AcServiceException {
return dao.readAuthorities();
}
@Override
public Authority getAuthorityByName(String name) throws AcServiceException {
return dao.readAuthorityByName(name);
}
@Override
public Authority getAuthorityByUrl(String name) throws AcServiceException {
return dao.readAuthorityByUrl(name);
}
@Override
public void createAuthority(Authority auth) throws AcServiceException {
dao.create(auth);
}
@Override
public String generateAuthToken() throws AcServiceException {
// TODO: check if already used
return new BigInteger(256, random).toString(16);
}
@Override
public void updateAuthority(Authority auth) throws AcServiceException {
dao.update(auth);
}
@Override
public void setAttribute(long userId, Attribute attribute)
throws AcServiceException {
if (attribute == null) {
throw new IllegalArgumentException("Attribute is not specified");
}
User user = dao.readUser(userId);
if (user == null) {
throw new IllegalArgumentException(
"The user with that ID doesn't exist");
}
int indexAttribute = user.getAttributes().indexOf(attribute);
if (indexAttribute == -1) {
user.getAttributes().add(attribute);
} else {
user.getAttributes().get(indexAttribute)
.setValue(attribute.getValue());
}
dao.update(user);
}
}
| true | true | public void updateUser(long userId, String authToken, Long expTime,
List<Attribute> attributes) throws AcServiceException {
User user = dao.readUser(userId);
if (user == null) {
throw new IllegalArgumentException(
"The user with that ID doesn't exist");
}
if (authToken != null) {
if (expTime == null) {
throw new IllegalArgumentException(
"The expiration time is not specified");
}
user.setAuthToken(authToken);
user.setExpTime(expTime);
}
List<Attribute> tmp = new LinkedList<Attribute>();
for (Attribute oldA : user.getAttributes()) {
Attribute remove = null;
for (Attribute newA : tmp) {
if (oldA.getAuthority().equals(newA.getAuthority())
&& oldA.getKey().equals(newA.getKey())) {
oldA.setValue(newA.getValue());
remove = newA;
break;
}
}
if (remove != null) {
tmp.remove(remove);
}
}
user.getAttributes().addAll(tmp);
dao.update(user);
}
| public void updateUser(long userId, String authToken, Long expTime,
List<Attribute> attributes) throws AcServiceException {
User user = dao.readUser(userId);
if (user == null) {
throw new IllegalArgumentException(
"The user with that ID doesn't exist");
}
if (authToken != null) {
if (expTime == null) {
throw new IllegalArgumentException(
"The expiration time is not specified");
}
user.setAuthToken(authToken);
}
if (expTime != null) {
user.setExpTime(expTime);
}
List<Attribute> tmp = new LinkedList<Attribute>();
for (Attribute oldA : user.getAttributes()) {
Attribute remove = null;
for (Attribute newA : tmp) {
if (oldA.getAuthority().equals(newA.getAuthority())
&& oldA.getKey().equals(newA.getKey())) {
oldA.setValue(newA.getValue());
remove = newA;
break;
}
}
if (remove != null) {
tmp.remove(remove);
}
}
user.getAttributes().addAll(tmp);
dao.update(user);
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/Caption.java b/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
index 8cd81ae88..f5ba082f7 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/Caption.java
@@ -1,151 +1,155 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.itmill.toolkit.terminal.gwt.client;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.HTML;
import com.itmill.toolkit.terminal.gwt.client.ui.Icon;
public class Caption extends HTML {
public static final String CLASSNAME = "i-caption";
private final Paintable owner;
private Element errorIndicatorElement;
private Icon icon;
private Element captionText;
private ErrorMessage errorMessage;
private final ApplicationConnection client;
public Caption(Paintable component, ApplicationConnection client) {
super();
this.client = client;
owner = component;
setStyleName(CLASSNAME);
}
public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
if (uidl.hasAttribute("error")) {
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
+ } else {
+ // Restore the indicator that was previously made invisible
+ DOM.setStyleAttribute(errorIndicatorElement, "display", "inline");
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
+ // Just make the error indicator element invisible
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
DOM.setInnerText(captionText, uidl.getStringAttribute("caption"));
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
}
public void onBrowserEvent(Event event) {
final Element target = DOM.eventGetTarget(event);
if (errorIndicatorElement != null
&& DOM.compare(target, errorIndicatorElement)) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER:
showErrorMessage();
break;
case Event.ONMOUSEOUT:
hideErrorMessage();
break;
case Event.ONCLICK:
ApplicationConnection.getConsole().log(
DOM.getInnerHTML(errorMessage.getElement()));
default:
break;
}
}
}
private void hideErrorMessage() {
if (errorMessage != null) {
errorMessage.hide();
}
}
private void showErrorMessage() {
if (errorMessage != null) {
errorMessage.showAt(errorIndicatorElement);
}
}
public static boolean isNeeded(UIDL uidl) {
if (uidl.getStringAttribute("caption") != null) {
return true;
}
if (uidl.hasAttribute("error")) {
return true;
}
if (uidl.hasAttribute("icon")) {
return true;
}
// TODO Description ??
return false;
}
/**
* Returns Paintable for which this Caption belongs to.
*
* @return owner Widget
*/
public Paintable getOwner() {
return owner;
}
}
| false | true | public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
if (uidl.hasAttribute("error")) {
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
DOM.setInnerText(captionText, uidl.getStringAttribute("caption"));
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
}
| public void updateCaption(UIDL uidl) {
setVisible(!uidl.getBooleanAttribute("invisible"));
setStyleName(getElement(), "i-disabled", uidl.hasAttribute("disabled"));
if (uidl.hasAttribute("error")) {
final UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.insertChild(getElement(), errorIndicatorElement, 0);
} else {
// Restore the indicator that was previously made invisible
DOM.setStyleAttribute(errorIndicatorElement, "display", "inline");
}
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
// Just make the error indicator element invisible
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.appendChild(getElement(), icon.getElement());
}
icon.setUri(uidl.getStringAttribute("icon"));
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
if (uidl.hasAttribute("caption")) {
if (captionText == null) {
captionText = DOM.createSpan();
DOM.appendChild(getElement(), captionText);
}
DOM.setInnerText(captionText, uidl.getStringAttribute("caption"));
} else {
// TODO should span also be removed
}
if (uidl.hasAttribute("description")) {
if (captionText != null) {
DOM.setElementProperty(captionText, "title", uidl
.getStringAttribute("description"));
} else {
setTitle(uidl.getStringAttribute("description"));
}
}
}
|
diff --git a/Freerider/src/no/ntnu/idi/socialhitchhiking/map/MapActivityAddPickupAndDropoff.java b/Freerider/src/no/ntnu/idi/socialhitchhiking/map/MapActivityAddPickupAndDropoff.java
index f8562dc..b522523 100644
--- a/Freerider/src/no/ntnu/idi/socialhitchhiking/map/MapActivityAddPickupAndDropoff.java
+++ b/Freerider/src/no/ntnu/idi/socialhitchhiking/map/MapActivityAddPickupAndDropoff.java
@@ -1,759 +1,758 @@
/**
* @contributor(s): Freerider Team (Group 4, IT2901 Fall 2012, NTNU)
* @version: 1.0
* Copyright (C) 2012 Freerider Team.
*
* Licensed under the Apache License, Version 2.0.
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied.
*
* See the License for the specific language governing permissions
* and limitations under the License.
*
*/
package no.ntnu.idi.socialhitchhiking.map;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import no.ntnu.idi.freerider.model.Car;
import no.ntnu.idi.freerider.model.Journey;
import no.ntnu.idi.freerider.model.Location;
import no.ntnu.idi.freerider.model.MapLocation;
import no.ntnu.idi.freerider.model.Notification;
import no.ntnu.idi.freerider.model.NotificationType;
import no.ntnu.idi.freerider.model.TripPreferences;
import no.ntnu.idi.freerider.model.User;
import no.ntnu.idi.freerider.protocol.CarRequest;
import no.ntnu.idi.freerider.protocol.CarResponse;
import no.ntnu.idi.freerider.protocol.NotificationRequest;
import no.ntnu.idi.freerider.protocol.PreferenceRequest;
import no.ntnu.idi.freerider.protocol.PreferenceResponse;
import no.ntnu.idi.freerider.protocol.Request;
import no.ntnu.idi.freerider.protocol.RequestType;
import no.ntnu.idi.freerider.protocol.Response;
import no.ntnu.idi.freerider.protocol.ResponseStatus;
import no.ntnu.idi.freerider.protocol.UserResponse;
import no.ntnu.idi.socialhitchhiking.client.RequestTask;
import org.apache.http.client.ClientProtocolException;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TabHost;
import android.widget.TextView;
import no.ntnu.idi.socialhitchhiking.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
/**
* The activity used when a user should select where he/she wants to be picked up (pickup point),
* and where he/she wants to be dropped off (dropoff point).
*
*/
public class MapActivityAddPickupAndDropoff extends MapActivityAbstract{
/**
* When this field is true, the user should select a pickup point, by touching the map.
*/
private boolean isSelectingPickupPoint = false;
/**
* When this field is true, the user should select a dropoff point, by touching the map.
*/
private boolean isSelectingDropoffPoint = false;
/**
* The button to be pressed when the user should select a pickup point.
*/
private Button btnSelectPickupPoint;
/**
* The button to be pressed when the user should select a dropoff point.
*/
private Button btnSelectDropoffPoint;
/**
* The button to press for sending a request.
*/
private Button btnSendRequest;
/**
* The selected pickup point.
*/
private Location pickupPoint;
/**
* The selected dropoff point.
*/
private Location dropoffPoint;
/**
* The color that pickup and dropoff button should have when they have been selected.
* Only one of the buttons will have this at the same time.
*/
private int selected = Color.argb(200, 170, 170, 250);
/**
* The color that pickup and dropoff button should have when they are <i>not</i> selected.
*/
private int notSelected = Color.argb(200, 200, 200, 200);
/**
* The {@link Overlay} that is used for drawing the pickup point.
* Is null when no pickup point is selected.
*/
private Overlay overlayPickupThumb = null;
/**
* The {@link Overlay} that is used for drawing the dropoff point.
* Is null when no dropoff point is selected.
*/
private Overlay overlayDropoffThumb = null;
/**
* The {@link ImageView} that is used to contain the profile picture of the driver.
*/
private ImageView picture;
/**
* The {@link AutoCompleteTextView} where the user can enter a pickup address
*/
private AutoCompleteTextView acPickup;
/**
* The {@link AutoCompleteTextView} where the user can enter a dropoff address
*/
private AutoCompleteTextView acDropoff;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Getting the selected journey
Journey journey = getApp().getSelectedJourney();
// Setting up tabs
TabHost tabs = (TabHost)findViewById(R.id.tabhost);
tabs.setup();
// Adding Ride tab
TabHost.TabSpec specRide = tabs.newTabSpec("tag1");
specRide.setContent(R.id.ride_tab);
specRide.setIndicator("Ride");
tabs.addTab(specRide);
// Adding Driver tab
TabHost.TabSpec specDriver = tabs.newTabSpec("tag2");
specDriver.setContent(R.id.driver_tab);
specDriver.setIndicator("Driver");
tabs.addTab(specDriver);
// Adding the pickup location address text
((AutoCompleteTextView)findViewById(R.id.pickupText)).setText(getIntent().getExtras().getString("pickupString"));
// Adding the dropoff location address text
((AutoCompleteTextView)findViewById(R.id.dropoffText)).setText(getIntent().getExtras().getString("dropoffString"));
// Drawing the pickup and dropoff locations on the map
setPickupLocation();
setDropOffLocation();
// Adding image of the driver
User driver = journey.getRoute().getOwner();
picture = (ImageView) findViewById(R.id.mapViewPickupImage);
// Create an object for subclass of AsyncTask
GetImage task = new GetImage(picture);
// Execute the task: Get image from url and add it to the ImageView
task.execute(driver.getPictureURL());
// Adding the name of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewName)).setText(driver.getFullName());
// Getting the drivers preferences
TripPreferences pref = new TripPreferences(777, true, true, true, true, true);
pref.setPrefId(1); //Dummy data
Request req = new PreferenceRequest(RequestType.GET_PREFERENCE, driver, pref);
PreferenceResponse res = null;
try {
res = (PreferenceResponse) RequestTask.sendRequest(req,getApp());
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the smoking preference
if(res.getPreferences().getSmoking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the animals preference
if(res.getPreferences().getAnimals()){
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the breaks preference
if(res.getPreferences().getBreaks()){
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the music preference
if(res.getPreferences().getMusic()){
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the talking preference
if(res.getPreferences().getTalking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the number of available seats
((TextView)findViewById(R.id.mapViewPickupTextViewSeats)).setText(res.getPreferences().getSeatsAvailable() + " available seats");
// Setting the age of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewAge)).setText("Age: " + driver.getAge());
// Adding the gender of the driver
if(driver.getGender() != null){
if(driver.getGender().equals("m")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.male);
}else if(driver.getGender().equals("f")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.female);
}
}
// Setting the drivers mobile number
((TextView)findViewById(R.id.mapViewPickupTextViewPhone)).setText("Mobile: " + driver.getPhone());
// Getting the car image
Car car = new Car(driver.getCarId(),"Dummy",0.0); //"Dummy" and 0.0 are dummy vars. getApp() etc sends the current user's carid
Request carReq = new CarRequest(RequestType.GET_CAR, getApp().getUser(), car);
try {
CarResponse carRes = (CarResponse) RequestTask.sendRequest(carReq,getApp());
Bitmap carImage = BitmapFactory.decodeByteArray(carRes.getCar().getPhoto(), 0, carRes.getCar().getPhoto().length);
// Setting the car image
((ImageView)findViewById(R.id.mapViewPickupImageViewCar)).setImageBitmap(carImage);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the car name
((TextView)findViewById(R.id.mapViewPickupTextViewCarName)).setText("Car type: " + car.getCarName());
// Setting the comfort
((RatingBar)findViewById(R.id.mapViewPickupAndDropoffComfortStars)).setRating((float) car.getComfort());
// Adding the date of ride
Date d = journey.getStart().getTime();
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm zzz");
String dateText = "Date: " + sdfDate.format(d);
String timeText = "Time: " + sdfTime.format(d);
((TextView)findViewById(R.id.mapViewPickupTextViewDate)).setText(dateText + "\n" + timeText);
//Adding Gender to the driver
ImageView iv_image;
iv_image = (ImageView) findViewById(R.id.gender);
try {
if (driver.getGender().equals("Male")){
Drawable male = getResources().getDrawable(R.drawable.male);
iv_image.setImageDrawable(male);
}
else if (driver.getGender().equals("Female")){
Drawable female = getResources().getDrawable(R.drawable.female);
iv_image.setImageDrawable(female);
}
} catch (NullPointerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Initializing the two autocomplete textviews pickup and dropoff
initAutocomplete();
// Adding onClickListener for the button "Ask for a ride"
btnSendRequest = (Button)findViewById(no.ntnu.idi.socialhitchhiking.R.id.mapViewPickupBtnSendRequest);
btnSendRequest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Response res;
NotificationRequest req;
if(pickupPoint == null || dropoffPoint == null){
makeToast("You have to choose pickup point and dropoff point.");
return;
}
inPickupMode = true;
String senderID = getApp().getUser().getID();
String recipientID = getApp().getSelectedJourney().getRoute().getOwner().getID();
String senderName = getApp().getUser().getFullName();
String comment = ((EditText)findViewById(R.id.mapViewPickupEtComment)).getText().toString();
int journeyID = getApp().getSelectedJourney().getSerial();
// Creating a new notification to be sendt to the driver
Notification n = new Notification(senderID, recipientID, senderName, comment, journeyID, NotificationType.HITCHHIKER_REQUEST, pickupPoint, dropoffPoint, Calendar.getInstance());
req = new NotificationRequest(RequestType.SEND_NOTIFICATION, getApp().getUser(), n);
// Sending notification
try {
res = RequestTask.sendRequest(req,getApp());
if(res instanceof UserResponse){
if(res.getStatus() == ResponseStatus.OK){
makeToast("Notification sent");
finish();
}
if(res.getStatus() == ResponseStatus.FAILED){
if(res.getErrorMessage().contains("no_duplicate_notifications")){
makeToast("You have already sent a request on this journey");
}
else{
makeToast("Could not send request");
}
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Adding buttons where you choose between pickup point and dropoff point
btnSelectPickupPoint = (Button)findViewById(R.id.mapViewPickupBtnPickup);
btnSelectDropoffPoint = (Button)findViewById(R.id.mapViewPickupBtnDropoff);
// Setting the selected pickup point
- //setSelectingPickupPoint();
btnSelectPickupPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = false;
isSelectingPickupPoint = true;
btnSelectPickupPoint.setBackgroundColor(selected);
btnSelectDropoffPoint.setBackgroundColor(notSelected);
makeToast("Press the map to add pickup location");
}
});
// Setting the selected dropoff point
btnSelectDropoffPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = true;
isSelectingPickupPoint = false;
btnSelectPickupPoint.setBackgroundColor(notSelected);
btnSelectDropoffPoint.setBackgroundColor(selected);
makeToast("Press the map to add dropoff location");
}
});
// Adding message to the user
makeToast("Please set a pickup and dropoff location.");
/*
Bundle extras = getIntent().getExtras();
if(extras != null){
Serializable ser1 = extras.getSerializable("searchFrom");
Serializable ser2 = extras.getSerializable("searchTo");
if(ser1 != null && ser1 instanceof Location){
drawThumb((Location)ser1, true);
}
if(ser2 != null && ser2 instanceof Location){
drawThumb((Location)ser2, false);
}
}*/
}
/**
* Initialize the {@link AutoCompleteTextView}'s with an {@link ArrayAdapter}
* and a listener ({@link AutoCompleteTextWatcher}). The listener gets autocomplete
* data from the Google Places API and updates the ArrayAdapter with these.
*/
private void initAutocomplete() {
adapter = new ArrayAdapter<String>(this,R.layout.item_list);
adapter.setNotifyOnChange(true);
acPickup = (AutoCompleteTextView) findViewById(R.id.pickupText);
acPickup.setAdapter(adapter);
acPickup.addTextChangedListener(new AutoCompleteTextWatcher(this, adapter, acPickup));
acPickup.setThreshold(1);
acPickup.selectAll();
acDropoff = (AutoCompleteTextView) findViewById(R.id.dropoffText);
acDropoff.setAdapter(adapter);
//acTo.addTextChangedListener(new AutoCompleteTextWatcher(this, adapter, acTo));
//adds the adapter for the textChangedListener
//acAdd.setAdapter(adapter);
acDropoff.addTextChangedListener(new AutoCompleteTextWatcher(this, adapter, acDropoff));
//sets the next button on the keyboard
acPickup.setOnEditorActionListener(new EditText.OnEditorActionListener(){
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_NEXT){
// Removes old pickup point
//setSelectingPickupPoint();
// Sets the pickup location
setPickupLocation();
// Sets focus to dropoff
acDropoff.requestFocus();
return true;
}
else{
return false;
}
}
});
//sets the done button on the keyboard
acDropoff.setOnEditorActionListener(new EditText.OnEditorActionListener(){
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE){
// Removes old pickup point
//setSelectingDropoffPoint();
// Sets the dropoff location
setDropOffLocation();
// Sets focus to "Comment to driver"
((EditText)findViewById(R.id.mapViewPickupEtComment)).requestFocus();
return true;
}
else{
return false;
}
}
});
}
/**
* Clearing the text in the pickup text field.
*/
public void clearPickupText(View v){
((EditText)findViewById(R.id.pickupText)).setText("");
}
/**
* Clearing the text in the dropoff text field.
*/
public void clearDropoffText(View v){
((EditText)findViewById(R.id.dropoffText)).setText("");
}
/**
* Should be called when both a pickup point and a dropoff point has been selected.
*/
/*private void setDoneSelecting(){
isSelectingPickupPoint = false;
isSelectingDropoffPoint = false;
btnSelectPickupPoint.setBackgroundColor(notSelected);
btnSelectDropoffPoint.setBackgroundColor(notSelected);
}*/
@Override
protected void initContentView() {
setContentView(R.layout.mapactivity_pickup_and_dropoff);
}
@Override
protected void initMapView() {
mapView = (MapView)findViewById(R.id.mapViewPickupAndDropoffMapView);
}
@Override
protected void initProgressBar() {
setProgressBar((ProgressBar)findViewById(R.id.mapViewPickupProgressBar));
}
/**
* This method loops trough the route path, to find out which {@link Location} is
* closest to the given {@link MapLocation}, and returns this.
*/
private Location findClosestLocationOnRoute(MapLocation ml){
List<Location> l = getApp().getSelectedJourney().getRoute().getRouteData();
Location lClosest = l.get(0);
for (int i = 0; i < l.size(); i++) {
lClosest = closest(ml, lClosest, l.get(i));
}
return lClosest;
}
/**
* Takes three parameters. Returns the one {@link Location}-parameter of the two last, that is closest
* to the first given {@link Location}.
*/
private static Location closest(Location loc, Location a, Location b){
android.location.Location location = new android.location.Location("");
location.setLatitude(loc.getLatitude());
location.setLongitude(loc.getLongitude());
android.location.Location lA = new android.location.Location("");
lA.setLatitude(a.getLatitude());
lA.setLongitude(a.getLongitude());
android.location.Location lB = new android.location.Location("");
lB.setLatitude(b.getLatitude());
lB.setLongitude(b.getLongitude());
float distA = location.distanceTo(lA);
float distB = location.distanceTo(lB);
if(distA < distB) return a;
return b;
}
/*
* (non-Javadoc)
* @see android.view.GestureDetector.OnGestureListener#onLongPress(android.view.MotionEvent)
*/
@Override
public void onLongPress(MotionEvent e) {
// Does nothing
}
/**
* Adds the pickup location to the map route.
*/
private void setPickupLocation(){
// Defines the AutoCompleteTextView pickupText
acPickup = (AutoCompleteTextView)findViewById(R.id.pickupText);
// Controls if the user has entered an address
if(!acPickup.getText().toString().equals("")){
// Gets the GeoPoint of the written address
GeoPoint pickupGeo = GeoHelper.getGeoPoint(acPickup.getText().toString());
// Gets the MapLocation of the GeoPoint
MapLocation mapLocation = (MapLocation) GeoHelper.getLocation(pickupGeo);
// Finds the pickup location on the route closest to the given address
Location temp = findClosestLocationOnRoute(mapLocation);
//Controls if the user has entered a NEW address
if(pickupPoint != temp){
// Removes old pickup point (thumb)
if(overlayPickupThumb != null){
mapView.getOverlays().remove(overlayPickupThumb);
overlayPickupThumb = null;
}
mapView.invalidate();
// If no dropoff point is specified, we add the pickup point to the map.
if(dropoffPoint == null){
pickupPoint = temp;
overlayPickupThumb = drawThumb(pickupPoint, true);
//setSelectingDropoffPoint();
}else{ // If a dropoff point is specified:
List<Location> l = getApp().getSelectedJourney().getRoute().getRouteData();
// Checks to make sure the pickup point is before the dropoff point.
if(l.indexOf(temp) < l.indexOf(dropoffPoint)){
makeToast("The pickup point has to be before the dropoff point");
}else{
// Adds the pickup point to the map by drawing a cross
pickupPoint = temp;
overlayPickupThumb = drawThumb(pickupPoint, true);
//setDoneSelecting();
}
}
}
}else{
makeToast("Please add a pickup address");
}
}
/**
* Adds the dropoff location to the map route.
*/
private void setDropOffLocation(){
// Defines the AutoCompleteTextView with the dropoff address
acDropoff = (AutoCompleteTextView)findViewById(R.id.dropoffText);
//Controls if the user has entered an address
if(!acDropoff.getText().toString().equals("")){
// Gets the GeoPoint of the given address
GeoPoint dropoffGeo = GeoHelper.getGeoPoint(acDropoff.getText().toString());
// Gets the MapLocation from the given GeoPoint
MapLocation mapLocation = (MapLocation) GeoHelper.getLocation(dropoffGeo);
// Finds the dropoff location on the route closest to the given address
Location temp = findClosestLocationOnRoute(mapLocation);
// Controls if the user has entered a NEW address
if(dropoffPoint != temp){
// Removes old pickup point (thumb)
if(overlayDropoffThumb != null){
mapView.getOverlays().remove(overlayDropoffThumb);
overlayDropoffThumb = null;
//pickupPoint = null;
}
mapView.invalidate();
// If no pickup point is specified, we add the dropoff point to the map.
if(pickupPoint == null){
dropoffPoint = temp;
overlayDropoffThumb = drawThumb(dropoffPoint, false);
//setSelectingPickupPoint();
}else{ // If a pickup point is specified:
List<Location> l = getApp().getSelectedJourney().getRoute().getRouteData();
// Checks to make sure the dropoff point is after the pickup point.
if(l.indexOf(temp) > l.indexOf(pickupPoint)){
makeToast("The droppoff point has to be after the pickup point");
}else{
// Adds the dropoff point to the map by drawing a cross
dropoffPoint = temp;
overlayDropoffThumb = drawThumb(dropoffPoint, false);
//setDoneSelecting();
}
}
}
}else{
makeToast("Please add a dropoff address");
}
}
/**
* When someone presses the map, this method is called and draws the pickup
* or dropoff point on the map depending on which of the {@link Button}s,
* {@link #btnSelectPickupPoint} or {@link #btnSelectDropoffPoint} that is pressed.
*/
@Override
public synchronized boolean onSingleTapUp(MotionEvent e) {
if(!isSelectingDropoffPoint && !isSelectingPickupPoint){
return false;
}
GeoPoint gp = mapView.getProjection().fromPixels(
(int) e.getX(),
(int) e.getY());
MapLocation mapLocation = (MapLocation) GeoHelper.getLocation(gp);
// If the user is selecting a pickup point
if(isSelectingPickupPoint){
Location temp = findClosestLocationOnRoute(mapLocation);
//Controls if the user has entered a NEW address
if(pickupPoint != temp){
// Removes old pickup point (thumb)
if(overlayPickupThumb != null){
mapView.getOverlays().remove(overlayPickupThumb);
overlayPickupThumb = null;
}
mapView.invalidate();
// If no dropoff point is specified, we add the pickup point to the map.
if(dropoffPoint == null){
pickupPoint = temp;
overlayPickupThumb = drawThumb(pickupPoint, true);
//setSelectingDropoffPoint();
}else{ // If a dropoff point is specified:
List<Location> l = getApp().getSelectedJourney().getRoute().getRouteData();
// Checks to make sure the pickup point is before the dropoff point.
if(l.indexOf(temp) < l.indexOf(dropoffPoint)){
makeToast("The pickup point has to be before the dropoff point");
}else{
// Adds the pickup point to the map by drawing a thumb
pickupPoint = temp;
overlayPickupThumb = drawThumb(pickupPoint, true);
//setDoneSelecting();
}
}
}
// If the user is selecting a dropoff point
}else if(isSelectingDropoffPoint){
Location temp = findClosestLocationOnRoute(mapLocation);
// Controls if the user has entered a NEW address
if(dropoffPoint != temp){
// Removes old dropoff point (thumb)
if(overlayDropoffThumb != null){
mapView.getOverlays().remove(overlayDropoffThumb);
overlayDropoffThumb = null;
//pickupPoint = null;
}
mapView.invalidate();
// If no pickup point is specified, we add the dropoff point to the map.
if(pickupPoint == null){
dropoffPoint = temp;
overlayDropoffThumb = drawThumb(dropoffPoint, false);
//setSelectingPickupPoint();
}else{ // If a pickup point is specified:
List<Location> l = getApp().getSelectedJourney().getRoute().getRouteData();
// Checks to make sure the dropoff point is after the pickup point.
if(l.indexOf(temp) > l.indexOf(pickupPoint)){
makeToast("The droppoff point has to be after the pickup point");
}else{
// Adds the dropoff point to the map by drawing a thumb
dropoffPoint = temp;
overlayDropoffThumb = drawThumb(dropoffPoint, false);
//setDoneSelecting();
}
}
}
}
return true;
}
}
| true | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Getting the selected journey
Journey journey = getApp().getSelectedJourney();
// Setting up tabs
TabHost tabs = (TabHost)findViewById(R.id.tabhost);
tabs.setup();
// Adding Ride tab
TabHost.TabSpec specRide = tabs.newTabSpec("tag1");
specRide.setContent(R.id.ride_tab);
specRide.setIndicator("Ride");
tabs.addTab(specRide);
// Adding Driver tab
TabHost.TabSpec specDriver = tabs.newTabSpec("tag2");
specDriver.setContent(R.id.driver_tab);
specDriver.setIndicator("Driver");
tabs.addTab(specDriver);
// Adding the pickup location address text
((AutoCompleteTextView)findViewById(R.id.pickupText)).setText(getIntent().getExtras().getString("pickupString"));
// Adding the dropoff location address text
((AutoCompleteTextView)findViewById(R.id.dropoffText)).setText(getIntent().getExtras().getString("dropoffString"));
// Drawing the pickup and dropoff locations on the map
setPickupLocation();
setDropOffLocation();
// Adding image of the driver
User driver = journey.getRoute().getOwner();
picture = (ImageView) findViewById(R.id.mapViewPickupImage);
// Create an object for subclass of AsyncTask
GetImage task = new GetImage(picture);
// Execute the task: Get image from url and add it to the ImageView
task.execute(driver.getPictureURL());
// Adding the name of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewName)).setText(driver.getFullName());
// Getting the drivers preferences
TripPreferences pref = new TripPreferences(777, true, true, true, true, true);
pref.setPrefId(1); //Dummy data
Request req = new PreferenceRequest(RequestType.GET_PREFERENCE, driver, pref);
PreferenceResponse res = null;
try {
res = (PreferenceResponse) RequestTask.sendRequest(req,getApp());
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the smoking preference
if(res.getPreferences().getSmoking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the animals preference
if(res.getPreferences().getAnimals()){
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the breaks preference
if(res.getPreferences().getBreaks()){
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the music preference
if(res.getPreferences().getMusic()){
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the talking preference
if(res.getPreferences().getTalking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the number of available seats
((TextView)findViewById(R.id.mapViewPickupTextViewSeats)).setText(res.getPreferences().getSeatsAvailable() + " available seats");
// Setting the age of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewAge)).setText("Age: " + driver.getAge());
// Adding the gender of the driver
if(driver.getGender() != null){
if(driver.getGender().equals("m")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.male);
}else if(driver.getGender().equals("f")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.female);
}
}
// Setting the drivers mobile number
((TextView)findViewById(R.id.mapViewPickupTextViewPhone)).setText("Mobile: " + driver.getPhone());
// Getting the car image
Car car = new Car(driver.getCarId(),"Dummy",0.0); //"Dummy" and 0.0 are dummy vars. getApp() etc sends the current user's carid
Request carReq = new CarRequest(RequestType.GET_CAR, getApp().getUser(), car);
try {
CarResponse carRes = (CarResponse) RequestTask.sendRequest(carReq,getApp());
Bitmap carImage = BitmapFactory.decodeByteArray(carRes.getCar().getPhoto(), 0, carRes.getCar().getPhoto().length);
// Setting the car image
((ImageView)findViewById(R.id.mapViewPickupImageViewCar)).setImageBitmap(carImage);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the car name
((TextView)findViewById(R.id.mapViewPickupTextViewCarName)).setText("Car type: " + car.getCarName());
// Setting the comfort
((RatingBar)findViewById(R.id.mapViewPickupAndDropoffComfortStars)).setRating((float) car.getComfort());
// Adding the date of ride
Date d = journey.getStart().getTime();
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm zzz");
String dateText = "Date: " + sdfDate.format(d);
String timeText = "Time: " + sdfTime.format(d);
((TextView)findViewById(R.id.mapViewPickupTextViewDate)).setText(dateText + "\n" + timeText);
//Adding Gender to the driver
ImageView iv_image;
iv_image = (ImageView) findViewById(R.id.gender);
try {
if (driver.getGender().equals("Male")){
Drawable male = getResources().getDrawable(R.drawable.male);
iv_image.setImageDrawable(male);
}
else if (driver.getGender().equals("Female")){
Drawable female = getResources().getDrawable(R.drawable.female);
iv_image.setImageDrawable(female);
}
} catch (NullPointerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Initializing the two autocomplete textviews pickup and dropoff
initAutocomplete();
// Adding onClickListener for the button "Ask for a ride"
btnSendRequest = (Button)findViewById(no.ntnu.idi.socialhitchhiking.R.id.mapViewPickupBtnSendRequest);
btnSendRequest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Response res;
NotificationRequest req;
if(pickupPoint == null || dropoffPoint == null){
makeToast("You have to choose pickup point and dropoff point.");
return;
}
inPickupMode = true;
String senderID = getApp().getUser().getID();
String recipientID = getApp().getSelectedJourney().getRoute().getOwner().getID();
String senderName = getApp().getUser().getFullName();
String comment = ((EditText)findViewById(R.id.mapViewPickupEtComment)).getText().toString();
int journeyID = getApp().getSelectedJourney().getSerial();
// Creating a new notification to be sendt to the driver
Notification n = new Notification(senderID, recipientID, senderName, comment, journeyID, NotificationType.HITCHHIKER_REQUEST, pickupPoint, dropoffPoint, Calendar.getInstance());
req = new NotificationRequest(RequestType.SEND_NOTIFICATION, getApp().getUser(), n);
// Sending notification
try {
res = RequestTask.sendRequest(req,getApp());
if(res instanceof UserResponse){
if(res.getStatus() == ResponseStatus.OK){
makeToast("Notification sent");
finish();
}
if(res.getStatus() == ResponseStatus.FAILED){
if(res.getErrorMessage().contains("no_duplicate_notifications")){
makeToast("You have already sent a request on this journey");
}
else{
makeToast("Could not send request");
}
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Adding buttons where you choose between pickup point and dropoff point
btnSelectPickupPoint = (Button)findViewById(R.id.mapViewPickupBtnPickup);
btnSelectDropoffPoint = (Button)findViewById(R.id.mapViewPickupBtnDropoff);
// Setting the selected pickup point
//setSelectingPickupPoint();
btnSelectPickupPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = false;
isSelectingPickupPoint = true;
btnSelectPickupPoint.setBackgroundColor(selected);
btnSelectDropoffPoint.setBackgroundColor(notSelected);
makeToast("Press the map to add pickup location");
}
});
// Setting the selected dropoff point
btnSelectDropoffPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = true;
isSelectingPickupPoint = false;
btnSelectPickupPoint.setBackgroundColor(notSelected);
btnSelectDropoffPoint.setBackgroundColor(selected);
makeToast("Press the map to add dropoff location");
}
});
// Adding message to the user
makeToast("Please set a pickup and dropoff location.");
/*
Bundle extras = getIntent().getExtras();
if(extras != null){
Serializable ser1 = extras.getSerializable("searchFrom");
Serializable ser2 = extras.getSerializable("searchTo");
if(ser1 != null && ser1 instanceof Location){
drawThumb((Location)ser1, true);
}
if(ser2 != null && ser2 instanceof Location){
drawThumb((Location)ser2, false);
}
}*/
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Getting the selected journey
Journey journey = getApp().getSelectedJourney();
// Setting up tabs
TabHost tabs = (TabHost)findViewById(R.id.tabhost);
tabs.setup();
// Adding Ride tab
TabHost.TabSpec specRide = tabs.newTabSpec("tag1");
specRide.setContent(R.id.ride_tab);
specRide.setIndicator("Ride");
tabs.addTab(specRide);
// Adding Driver tab
TabHost.TabSpec specDriver = tabs.newTabSpec("tag2");
specDriver.setContent(R.id.driver_tab);
specDriver.setIndicator("Driver");
tabs.addTab(specDriver);
// Adding the pickup location address text
((AutoCompleteTextView)findViewById(R.id.pickupText)).setText(getIntent().getExtras().getString("pickupString"));
// Adding the dropoff location address text
((AutoCompleteTextView)findViewById(R.id.dropoffText)).setText(getIntent().getExtras().getString("dropoffString"));
// Drawing the pickup and dropoff locations on the map
setPickupLocation();
setDropOffLocation();
// Adding image of the driver
User driver = journey.getRoute().getOwner();
picture = (ImageView) findViewById(R.id.mapViewPickupImage);
// Create an object for subclass of AsyncTask
GetImage task = new GetImage(picture);
// Execute the task: Get image from url and add it to the ImageView
task.execute(driver.getPictureURL());
// Adding the name of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewName)).setText(driver.getFullName());
// Getting the drivers preferences
TripPreferences pref = new TripPreferences(777, true, true, true, true, true);
pref.setPrefId(1); //Dummy data
Request req = new PreferenceRequest(RequestType.GET_PREFERENCE, driver, pref);
PreferenceResponse res = null;
try {
res = (PreferenceResponse) RequestTask.sendRequest(req,getApp());
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the smoking preference
if(res.getPreferences().getSmoking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewSmokingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the animals preference
if(res.getPreferences().getAnimals()){
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewAnimalsIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the breaks preference
if(res.getPreferences().getBreaks()){
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewBreaksIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the music preference
if(res.getPreferences().getMusic()){
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the talking preference
if(res.getPreferences().getTalking()){
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.green_check);
}else{
((ImageView)findViewById(R.id.mapViewPickupImageViewTalkingIcon)).setImageResource(R.drawable.red_cross);
}
// Setting the number of available seats
((TextView)findViewById(R.id.mapViewPickupTextViewSeats)).setText(res.getPreferences().getSeatsAvailable() + " available seats");
// Setting the age of the driver
((TextView)findViewById(R.id.mapViewPickupTextViewAge)).setText("Age: " + driver.getAge());
// Adding the gender of the driver
if(driver.getGender() != null){
if(driver.getGender().equals("m")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.male);
}else if(driver.getGender().equals("f")){
((ImageView)findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.female);
}
}
// Setting the drivers mobile number
((TextView)findViewById(R.id.mapViewPickupTextViewPhone)).setText("Mobile: " + driver.getPhone());
// Getting the car image
Car car = new Car(driver.getCarId(),"Dummy",0.0); //"Dummy" and 0.0 are dummy vars. getApp() etc sends the current user's carid
Request carReq = new CarRequest(RequestType.GET_CAR, getApp().getUser(), car);
try {
CarResponse carRes = (CarResponse) RequestTask.sendRequest(carReq,getApp());
Bitmap carImage = BitmapFactory.decodeByteArray(carRes.getCar().getPhoto(), 0, carRes.getCar().getPhoto().length);
// Setting the car image
((ImageView)findViewById(R.id.mapViewPickupImageViewCar)).setImageBitmap(carImage);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Setting the car name
((TextView)findViewById(R.id.mapViewPickupTextViewCarName)).setText("Car type: " + car.getCarName());
// Setting the comfort
((RatingBar)findViewById(R.id.mapViewPickupAndDropoffComfortStars)).setRating((float) car.getComfort());
// Adding the date of ride
Date d = journey.getStart().getTime();
SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm zzz");
String dateText = "Date: " + sdfDate.format(d);
String timeText = "Time: " + sdfTime.format(d);
((TextView)findViewById(R.id.mapViewPickupTextViewDate)).setText(dateText + "\n" + timeText);
//Adding Gender to the driver
ImageView iv_image;
iv_image = (ImageView) findViewById(R.id.gender);
try {
if (driver.getGender().equals("Male")){
Drawable male = getResources().getDrawable(R.drawable.male);
iv_image.setImageDrawable(male);
}
else if (driver.getGender().equals("Female")){
Drawable female = getResources().getDrawable(R.drawable.female);
iv_image.setImageDrawable(female);
}
} catch (NullPointerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Initializing the two autocomplete textviews pickup and dropoff
initAutocomplete();
// Adding onClickListener for the button "Ask for a ride"
btnSendRequest = (Button)findViewById(no.ntnu.idi.socialhitchhiking.R.id.mapViewPickupBtnSendRequest);
btnSendRequest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Response res;
NotificationRequest req;
if(pickupPoint == null || dropoffPoint == null){
makeToast("You have to choose pickup point and dropoff point.");
return;
}
inPickupMode = true;
String senderID = getApp().getUser().getID();
String recipientID = getApp().getSelectedJourney().getRoute().getOwner().getID();
String senderName = getApp().getUser().getFullName();
String comment = ((EditText)findViewById(R.id.mapViewPickupEtComment)).getText().toString();
int journeyID = getApp().getSelectedJourney().getSerial();
// Creating a new notification to be sendt to the driver
Notification n = new Notification(senderID, recipientID, senderName, comment, journeyID, NotificationType.HITCHHIKER_REQUEST, pickupPoint, dropoffPoint, Calendar.getInstance());
req = new NotificationRequest(RequestType.SEND_NOTIFICATION, getApp().getUser(), n);
// Sending notification
try {
res = RequestTask.sendRequest(req,getApp());
if(res instanceof UserResponse){
if(res.getStatus() == ResponseStatus.OK){
makeToast("Notification sent");
finish();
}
if(res.getStatus() == ResponseStatus.FAILED){
if(res.getErrorMessage().contains("no_duplicate_notifications")){
makeToast("You have already sent a request on this journey");
}
else{
makeToast("Could not send request");
}
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Adding buttons where you choose between pickup point and dropoff point
btnSelectPickupPoint = (Button)findViewById(R.id.mapViewPickupBtnPickup);
btnSelectDropoffPoint = (Button)findViewById(R.id.mapViewPickupBtnDropoff);
// Setting the selected pickup point
btnSelectPickupPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = false;
isSelectingPickupPoint = true;
btnSelectPickupPoint.setBackgroundColor(selected);
btnSelectDropoffPoint.setBackgroundColor(notSelected);
makeToast("Press the map to add pickup location");
}
});
// Setting the selected dropoff point
btnSelectDropoffPoint.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
isSelectingDropoffPoint = true;
isSelectingPickupPoint = false;
btnSelectPickupPoint.setBackgroundColor(notSelected);
btnSelectDropoffPoint.setBackgroundColor(selected);
makeToast("Press the map to add dropoff location");
}
});
// Adding message to the user
makeToast("Please set a pickup and dropoff location.");
/*
Bundle extras = getIntent().getExtras();
if(extras != null){
Serializable ser1 = extras.getSerializable("searchFrom");
Serializable ser2 = extras.getSerializable("searchTo");
if(ser1 != null && ser1 instanceof Location){
drawThumb((Location)ser1, true);
}
if(ser2 != null && ser2 instanceof Location){
drawThumb((Location)ser2, false);
}
}*/
}
|
diff --git a/src/main/java/com/alta189/simplesave/internal/SerializedClassBuilder.java b/src/main/java/com/alta189/simplesave/internal/SerializedClassBuilder.java
index 600772a..76a2f80 100644
--- a/src/main/java/com/alta189/simplesave/internal/SerializedClassBuilder.java
+++ b/src/main/java/com/alta189/simplesave/internal/SerializedClassBuilder.java
@@ -1,92 +1,92 @@
/*
* This file is part of SimpleSave
*
* SimpleSave is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SimpleSave is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.alta189.simplesave.internal;
import com.alta189.simplesave.exceptions.SerializeException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class SerializedClassBuilder {
public static boolean validClass(Class<?> clazz) {
try {
Method serialize = clazz.getDeclaredMethod("serialize");
if (!serialize.getReturnType().equals(String.class)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because it does not return a String");
return false;
}
if (!Modifier.isPublic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is not public");
return false;
}
if (!Modifier.isStatic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is static");
return false;
}
Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
if (!deserialize.getReturnType().equals(clazz)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' does not return the class '" + clazz.getCanonicalName() + "'");
return false;
}
if (!Modifier.isStatic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not static");
return false;
}
if (!Modifier.isPublic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not public");
return false;
}
} catch (NoSuchMethodException e) {
- System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is does not have either the serialize and/or deserialize method(s)");
+ System.out.println("Class '" + clazz.getCanonicalName() + "' does not have either the serialize and/or deserialize method(s)");
return false;
}
return true;
}
public static Object deserialize(Class<?> clazz, String data) {
try {
Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
deserialize.setAccessible(true);
return deserialize.invoke(null, data);
} catch (NoSuchMethodException e) {
throw new SerializeException("Could not deserialize data", e.getCause());
} catch (InvocationTargetException e) {
throw new SerializeException("Could not deserialize data", e.getCause());
} catch (IllegalAccessException e) {
throw new SerializeException("Could not deserialize data", e.getCause());
}
}
public static String serialize(Class<?> clazz, Object object) {
try {
Method serialize = clazz.getDeclaredMethod("serialize");
serialize.setAccessible(true);
return (String) serialize.invoke(object);
} catch (NoSuchMethodException e) {
throw new SerializeException("Could not serialize Class '" + clazz.getCanonicalName() + "'", e.getCause());
} catch (InvocationTargetException e) {
throw new SerializeException("Could not serialize Class '" + clazz.getCanonicalName() + "'", e.getCause());
} catch (IllegalAccessException e) {
throw new SerializeException("Could not serialize Class '" + clazz.getCanonicalName() + "'", e.getCause());
} catch (ClassCastException e) {
throw new SerializeException("Could not serialize Class '" + clazz.getCanonicalName() + "'", e.getCause());
}
}
}
| true | true | public static boolean validClass(Class<?> clazz) {
try {
Method serialize = clazz.getDeclaredMethod("serialize");
if (!serialize.getReturnType().equals(String.class)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because it does not return a String");
return false;
}
if (!Modifier.isPublic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is not public");
return false;
}
if (!Modifier.isStatic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is static");
return false;
}
Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
if (!deserialize.getReturnType().equals(clazz)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' does not return the class '" + clazz.getCanonicalName() + "'");
return false;
}
if (!Modifier.isStatic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not static");
return false;
}
if (!Modifier.isPublic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not public");
return false;
}
} catch (NoSuchMethodException e) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is does not have either the serialize and/or deserialize method(s)");
return false;
}
return true;
}
| public static boolean validClass(Class<?> clazz) {
try {
Method serialize = clazz.getDeclaredMethod("serialize");
if (!serialize.getReturnType().equals(String.class)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because it does not return a String");
return false;
}
if (!Modifier.isPublic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is not public");
return false;
}
if (!Modifier.isStatic(serialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not serializable because the method 'serialize' is static");
return false;
}
Method deserialize = clazz.getDeclaredMethod("deserialize", String.class);
if (!deserialize.getReturnType().equals(clazz)) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' does not return the class '" + clazz.getCanonicalName() + "'");
return false;
}
if (!Modifier.isStatic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not static");
return false;
}
if (!Modifier.isPublic(deserialize.getModifiers())) {
System.out.println("Class '" + clazz.getCanonicalName() + "' is not deserializable because the method 'deserialize' is not public");
return false;
}
} catch (NoSuchMethodException e) {
System.out.println("Class '" + clazz.getCanonicalName() + "' does not have either the serialize and/or deserialize method(s)");
return false;
}
return true;
}
|
diff --git a/sandbox-providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceAdapterLiveTest.java b/sandbox-providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceAdapterLiveTest.java
index 04f4382d1d..afb9de6ac6 100644
--- a/sandbox-providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceAdapterLiveTest.java
+++ b/sandbox-providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceAdapterLiveTest.java
@@ -1,126 +1,124 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jclouds.softlayer.compute;
import static org.jclouds.softlayer.predicates.ProductItemPredicates.categoryCode;
import static org.jclouds.softlayer.predicates.ProductItemPredicates.units;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.net.IPSocket;
import org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;
import org.jclouds.softlayer.compute.strategy.SoftLayerComputeServiceAdapter;
import org.jclouds.softlayer.domain.ProductItem;
import org.jclouds.softlayer.domain.VirtualGuest;
import org.jclouds.softlayer.features.BaseSoftLayerClientLiveTest;
import org.jclouds.softlayer.features.ProductPackageClientLiveTest;
import org.jclouds.ssh.SshClient;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.net.InetAddresses;
@Test(groups = "live", singleThreaded = true, testName = "SoftLayerComputeServiceAdapterLiveTest")
public class SoftLayerComputeServiceAdapterLiveTest extends BaseSoftLayerClientLiveTest {
private SoftLayerComputeServiceAdapter adapter;
private VirtualGuest guest;
@BeforeGroups(groups = { "live" })
public void setupClient() {
super.setupClient();
adapter = new SoftLayerComputeServiceAdapter(context.getApi(),
ProductPackageClientLiveTest.CLOUD_SERVER_PACKAGE_NAME,
new SoftLayerComputeServiceAdapter.VirtualGuestHasLoginDetailsPresent(context.getApi()),60*60*1000);
}
@Test
public void testListLocations() {
assertFalse(Iterables.isEmpty(adapter.listLocations()));
}
@Test
public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {
String group = "foo";
String name = "node"+new Random().nextInt();
- Template template = computeContext.getComputeService().templateBuilder()
- .locationId("3") // the default (singapore) doesn't work.
- .build();
+ Template template = computeContext.getComputeService().templateBuilder().build();
// test passing custom options
template.getOptions().as(SoftLayerTemplateOptions.class).domainName("me.org");
Map<String, Credentials> credentialStore = Maps.newLinkedHashMap();
guest = adapter.createNodeWithGroupEncodedIntoNameThenStoreCredentials(group, name, template, credentialStore);
assertEquals(guest.getHostname(), name);
assertEquals(guest.getDomain(), template.getOptions().as(SoftLayerTemplateOptions.class).getDomainName());
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
assert credentialStore.containsKey("node#" + guest.getId()) : "credentials to log into guest not found " + guest;
assert InetAddresses.isInetAddress(guest.getPrimaryBackendIpAddress()) : guest;
doConnectViaSsh(guest, credentialStore.get("node#" + guest.getId()));
}
protected void doConnectViaSsh(VirtualGuest guest, Credentials creds) {
SshClient ssh = computeContext.utils().sshFactory()
.create(new IPSocket(guest.getPrimaryIpAddress(), 22), creds);
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
System.err.println(ssh.exec("df -k").getOutput());
System.err.println(ssh.exec("mount").getOutput());
System.err.println(ssh.exec("uname -a").getOutput());
} finally {
if (ssh != null)
ssh.disconnect();
}
}
@Test
public void testListHardwareProfiles() {
Iterable<Set<ProductItem>> profiles = adapter.listHardwareProfiles();
assertFalse(Iterables.isEmpty(profiles));
for (Set<ProductItem> profile : profiles) {
// CPU, RAM and Volume
assertEquals(profile.size(), 3);
ProductItem cpuItem = Iterables.getOnlyElement(Iterables.filter(profile, units("PRIVATE_CORE")));
ProductItem ramItem = Iterables.getOnlyElement(Iterables.filter(profile, categoryCode("ram")));
assertEquals(cpuItem.getCapacity(), ramItem.getCapacity());
}
}
@AfterGroups(groups = "live")
protected void tearDown() {
if (guest != null)
adapter.destroyNode(guest.getId() + "");
super.tearDown();
}
}
| true | true | public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {
String group = "foo";
String name = "node"+new Random().nextInt();
Template template = computeContext.getComputeService().templateBuilder()
.locationId("3") // the default (singapore) doesn't work.
.build();
// test passing custom options
template.getOptions().as(SoftLayerTemplateOptions.class).domainName("me.org");
Map<String, Credentials> credentialStore = Maps.newLinkedHashMap();
guest = adapter.createNodeWithGroupEncodedIntoNameThenStoreCredentials(group, name, template, credentialStore);
assertEquals(guest.getHostname(), name);
assertEquals(guest.getDomain(), template.getOptions().as(SoftLayerTemplateOptions.class).getDomainName());
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
assert credentialStore.containsKey("node#" + guest.getId()) : "credentials to log into guest not found " + guest;
assert InetAddresses.isInetAddress(guest.getPrimaryBackendIpAddress()) : guest;
doConnectViaSsh(guest, credentialStore.get("node#" + guest.getId()));
}
| public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {
String group = "foo";
String name = "node"+new Random().nextInt();
Template template = computeContext.getComputeService().templateBuilder().build();
// test passing custom options
template.getOptions().as(SoftLayerTemplateOptions.class).domainName("me.org");
Map<String, Credentials> credentialStore = Maps.newLinkedHashMap();
guest = adapter.createNodeWithGroupEncodedIntoNameThenStoreCredentials(group, name, template, credentialStore);
assertEquals(guest.getHostname(), name);
assertEquals(guest.getDomain(), template.getOptions().as(SoftLayerTemplateOptions.class).getDomainName());
// check other things, like cpu correct, mem correct, image/os is correct
// (as possible)
assert credentialStore.containsKey("node#" + guest.getId()) : "credentials to log into guest not found " + guest;
assert InetAddresses.isInetAddress(guest.getPrimaryBackendIpAddress()) : guest;
doConnectViaSsh(guest, credentialStore.get("node#" + guest.getId()));
}
|
diff --git a/org/mailster/message/SmtpHeaders.java b/org/mailster/message/SmtpHeaders.java
index e2318f4..589fcab 100644
--- a/org/mailster/message/SmtpHeaders.java
+++ b/org/mailster/message/SmtpHeaders.java
@@ -1,258 +1,258 @@
package org.mailster.message;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.StringTokenizer;
/**
* ---<br>
* Mailster (C) 2007-2009 De Oliveira Edouard
* <p>
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 675 Mass
* Ave, Cambridge, MA 02139, USA.
* <p>
* See <a href="http://tedorg.free.fr/en/projects.php" target="_parent">Mailster
* Web Site</a> <br>
* ---
* <p>
* SmtpHeaders.java - Enter your Comment HERE.
*
* @author <a href="mailto:[email protected]">Edouard De Oliveira</a>
* @version $Revision$, $Date$
*/
public class SmtpHeaders
implements SmtpHeadersInterface, Serializable
{
private static final long serialVersionUID = -7375329552875800307L;
/**
* Headers: Map of List of String hashed on header name.
*/
private LinkedHashMap<String, SmtpHeader> headers = new LinkedHashMap<String, SmtpHeader>(10);
private transient String lastHeaderName;
public class SmtpHeader implements Serializable
{
private static final long serialVersionUID = 7734729823787943541L;
private String name;
private List<String> values;
public SmtpHeader(String name, List<String> values)
{
this.name = name;
this.values = values;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
protected List<String> getValues()
{
return values;
}
public void setValues(List<String> values)
{
this.values = values;
}
public String toString()
{
StringBuilder sb = new StringBuilder(getName());
sb.append(": ");
Iterator<String> it = values.iterator();
while (it.hasNext())
{
String value = it.next();
if (value.charAt(0) == '\t')
sb.append('\n');
sb.append(value);
if (it.hasNext())
sb.append("; ");
}
return sb.toString();
}
}
public SmtpHeaders()
{
}
/**
* Get the value(s) associated with the given header name.
* Header values are trimed.
*
* @param name header name
* @return value(s) associated with the header name
*/
public String[] getHeaderValues(String name)
{
return getHeaderValues(name, (name == null || !name.startsWith("X-")));
}
/**
* Get the value(s) associated with the given header name.
*
* @param name header name
* @param trimed if <code>true</code> the header value is trimed.
* @return value(s) associated with the header name
*/
private String[] getHeaderValues(String name, boolean trimed)
{
SmtpHeader h = headers.get(name);
if (h == null || h.getValues() == null)
return new String[0];
else
{
if (trimed)
{
String[] vals = new String[h.getValues().size()];
int i=0;
for (String s : h.getValues())
{
vals[i] = s.trim();
i+=1;
}
return vals;
}
else
return h.getValues().toArray(new String[h.getValues().size()]);
}
}
/**
* Get the first value associated with a given header name.
*
* @param name header name
* @return first value associated with the header name
*/
public String getHeaderValue(String name)
{
try
{
return headers.get(name).getValues().get(0).trim();
}
catch (Exception ex)
{
return null;
}
}
/**
* Adds a header to the Map.
*/
public void addHeader(String name, String value)
{
List<String> vals = new ArrayList<String>(1);
vals.add(value);
headers.put(name, new SmtpHeader(name, vals));
}
/**
* Adds a header to the Map.
*/
public void addHeaderLine(String line)
{
if (line != null && !"".equals(line))
{
int pos = line.indexOf(": ");
int termPos = line.indexOf(' ');
if (pos > 0 && (termPos == -1 || pos < termPos))
{
line = line.trim();
String name = line.substring(0, pos);
List<String> vals = new ArrayList<String>();
if (line.length() >= pos + 2)
{
line = line.substring(pos + 2);
if (name.equals(lastHeaderName))
{
SmtpHeader h = (SmtpHeader) headers.get(name);
if (h != null)
{
h.getValues().add(line);
return;
}
else
vals.add(line);
}
else
{
lastHeaderName = name;
if (lastHeaderName.startsWith("X-"))
// eXtended header so leave it intact
vals.add(line);
else
parseMultipleValues(line, vals);
}
}
headers.put(name, new SmtpHeader(name, vals));
}
else
{
// Additional header value
SmtpHeader h = headers.get(lastHeaderName);
if (lastHeaderName.startsWith("X-"))
h.getValues().add(line);
else if (SmtpHeadersInterface.SUBJECT.equals(lastHeaderName))
- h.getValues().add(line);
+ h.getValues().set(0, h.getValues().get(0)+'\n'+line);
else
parseMultipleValues(line, h.getValues());
}
}
}
private void parseMultipleValues(String lineToParse, List<String> vals)
{
StringTokenizer tk = new StringTokenizer(lineToParse, ";");
while (tk.hasMoreTokens())
vals.add(tk.nextToken().trim());
}
public String toString()
{
StringBuilder sb = new StringBuilder();
for (Iterator<SmtpHeader> i = headers.values().iterator(); i.hasNext();)
{
SmtpHeader hdr = i.next();
sb.append(hdr);
if (i.hasNext())
sb.append('\n');
}
return sb.toString();
}
}
| true | true | public void addHeaderLine(String line)
{
if (line != null && !"".equals(line))
{
int pos = line.indexOf(": ");
int termPos = line.indexOf(' ');
if (pos > 0 && (termPos == -1 || pos < termPos))
{
line = line.trim();
String name = line.substring(0, pos);
List<String> vals = new ArrayList<String>();
if (line.length() >= pos + 2)
{
line = line.substring(pos + 2);
if (name.equals(lastHeaderName))
{
SmtpHeader h = (SmtpHeader) headers.get(name);
if (h != null)
{
h.getValues().add(line);
return;
}
else
vals.add(line);
}
else
{
lastHeaderName = name;
if (lastHeaderName.startsWith("X-"))
// eXtended header so leave it intact
vals.add(line);
else
parseMultipleValues(line, vals);
}
}
headers.put(name, new SmtpHeader(name, vals));
}
else
{
// Additional header value
SmtpHeader h = headers.get(lastHeaderName);
if (lastHeaderName.startsWith("X-"))
h.getValues().add(line);
else if (SmtpHeadersInterface.SUBJECT.equals(lastHeaderName))
h.getValues().add(line);
else
parseMultipleValues(line, h.getValues());
}
}
}
| public void addHeaderLine(String line)
{
if (line != null && !"".equals(line))
{
int pos = line.indexOf(": ");
int termPos = line.indexOf(' ');
if (pos > 0 && (termPos == -1 || pos < termPos))
{
line = line.trim();
String name = line.substring(0, pos);
List<String> vals = new ArrayList<String>();
if (line.length() >= pos + 2)
{
line = line.substring(pos + 2);
if (name.equals(lastHeaderName))
{
SmtpHeader h = (SmtpHeader) headers.get(name);
if (h != null)
{
h.getValues().add(line);
return;
}
else
vals.add(line);
}
else
{
lastHeaderName = name;
if (lastHeaderName.startsWith("X-"))
// eXtended header so leave it intact
vals.add(line);
else
parseMultipleValues(line, vals);
}
}
headers.put(name, new SmtpHeader(name, vals));
}
else
{
// Additional header value
SmtpHeader h = headers.get(lastHeaderName);
if (lastHeaderName.startsWith("X-"))
h.getValues().add(line);
else if (SmtpHeadersInterface.SUBJECT.equals(lastHeaderName))
h.getValues().set(0, h.getValues().get(0)+'\n'+line);
else
parseMultipleValues(line, h.getValues());
}
}
}
|
diff --git a/soapui/src/main/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/basic/XPathContainsAssertion.java b/soapui/src/main/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/basic/XPathContainsAssertion.java
index d0a56ba7d..d25a1d759 100644
--- a/soapui/src/main/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/basic/XPathContainsAssertion.java
+++ b/soapui/src/main/java/com/eviware/soapui/impl/wsdl/teststeps/assertions/basic/XPathContainsAssertion.java
@@ -1,865 +1,865 @@
/*
* SoapUI, copyright (C) 2004-2012 smartbear.com
*
* SoapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* SoapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.teststeps.assertions.basic;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import junit.framework.ComparisonFailure;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlAnySimpleType;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlQName;
import org.apache.xmlbeans.impl.values.XmlValueDisconnectedException;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.custommonkey.xmlunit.DifferenceEngine;
import org.custommonkey.xmlunit.DifferenceListener;
import org.custommonkey.xmlunit.XMLAssert;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.config.TestAssertionConfig;
import com.eviware.soapui.impl.support.actions.ShowOnlineHelpAction;
import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.panels.assertions.AssertionCategoryMapping;
import com.eviware.soapui.impl.wsdl.panels.assertions.AssertionListEntry;
import com.eviware.soapui.impl.wsdl.support.HelpUrls;
import com.eviware.soapui.impl.wsdl.support.assertions.AssertedXPathImpl;
import com.eviware.soapui.impl.wsdl.support.assertions.AssertedXPathsContainer;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlMessageAssertion;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep;
import com.eviware.soapui.impl.wsdl.teststeps.assertions.AbstractTestAssertionFactory;
import com.eviware.soapui.model.TestModelItem;
import com.eviware.soapui.model.TestPropertyHolder;
import com.eviware.soapui.model.iface.MessageExchange;
import com.eviware.soapui.model.iface.SubmitContext;
import com.eviware.soapui.model.propertyexpansion.PropertyExpander;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansion;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils;
import com.eviware.soapui.model.support.XPathReference;
import com.eviware.soapui.model.support.XPathReferenceContainer;
import com.eviware.soapui.model.support.XPathReferenceImpl;
import com.eviware.soapui.model.testsuite.Assertable;
import com.eviware.soapui.model.testsuite.AssertionError;
import com.eviware.soapui.model.testsuite.AssertionException;
import com.eviware.soapui.model.testsuite.RequestAssertion;
import com.eviware.soapui.model.testsuite.ResponseAssertion;
import com.eviware.soapui.model.testsuite.TestProperty;
import com.eviware.soapui.support.StringUtils;
import com.eviware.soapui.support.Tools;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.components.JUndoableTextArea;
import com.eviware.soapui.support.components.JXToolBar;
import com.eviware.soapui.support.types.StringList;
import com.eviware.soapui.support.xml.XmlObjectConfigurationBuilder;
import com.eviware.soapui.support.xml.XmlObjectConfigurationReader;
import com.eviware.soapui.support.xml.XmlUtils;
import com.jgoodies.forms.builder.ButtonBarBuilder;
/**
* Assertion that matches a specified XPath expression and its expected result
* against the associated WsdlTestRequests response message
*
* @author Ole.Matzura
*/
public class XPathContainsAssertion extends WsdlMessageAssertion implements RequestAssertion, ResponseAssertion,
XPathReferenceContainer
{
private final static Logger log = Logger.getLogger( XPathContainsAssertion.class );
private String expectedContent;
private String path;
private JDialog configurationDialog;
private JTextArea pathArea;
private JTextArea contentArea;
private boolean configureResult;
private boolean allowWildcards;
private boolean ignoreNamespaceDifferences;
private boolean ignoreComments;
public static final String ID = "XPath Match";
public static final String LABEL = "XPath Match";
public static final String DESCRIPTION = "Uses an XPath expression to select content from the target property and compares the result to an expected value. Applicable to any property containing XML.";
private JCheckBox allowWildcardsCheckBox;
private JCheckBox ignoreNamespaceDifferencesCheckBox;
private JCheckBox ignoreCommentsCheckBox;
public XPathContainsAssertion( TestAssertionConfig assertionConfig, Assertable assertable )
{
super( assertionConfig, assertable, true, true, true, true );
XmlObjectConfigurationReader reader = new XmlObjectConfigurationReader( getConfiguration() );
path = reader.readString( "path", null );
expectedContent = reader.readString( "content", null );
allowWildcards = reader.readBoolean( "allowWildcards", false );
ignoreNamespaceDifferences = reader.readBoolean( "ignoreNamspaceDifferences", false );
ignoreComments = reader.readBoolean( "ignoreComments", false );
}
public String getExpectedContent()
{
return expectedContent;
}
public void setExpectedContent( String expectedContent )
{
setExpectedContent( expectedContent, true );
}
/**
* @deprecated
*/
@Deprecated
public void setContent( String content )
{
setExpectedContent( content );
}
public String getPath()
{
return path;
}
public void setPath( String path )
{
this.path = path;
setConfiguration( createConfiguration() );
}
public boolean isAllowWildcards()
{
return allowWildcards;
}
public void setAllowWildcards( boolean allowWildcards )
{
this.allowWildcards = allowWildcards;
setConfiguration( createConfiguration() );
}
public boolean isIgnoreNamespaceDifferences()
{
return ignoreNamespaceDifferences;
}
public void setIgnoreNamespaceDifferences( boolean ignoreNamespaceDifferences )
{
this.ignoreNamespaceDifferences = ignoreNamespaceDifferences;
setConfiguration( createConfiguration() );
}
public boolean isIgnoreComments()
{
return ignoreComments;
}
public void setIgnoreComments( boolean ignoreComments )
{
this.ignoreComments = ignoreComments;
setConfiguration( createConfiguration() );
}
@Override
protected String internalAssertResponse( MessageExchange messageExchange, SubmitContext context )
throws AssertionException
{
if( !messageExchange.hasResponse() )
return "Missing Response";
else
return assertContent( messageExchange.getResponseContentAsXml(), context, "Response" );
}
protected String internalAssertProperty( TestPropertyHolder source, String propertyName,
MessageExchange messageExchange, SubmitContext context ) throws AssertionException
{
if( !XmlUtils.seemsToBeXml( source.getPropertyValue( propertyName ) ) )
{
throw new AssertionException( new AssertionError( "Property '" + propertyName
+ "' has value which is not xml!" ) );
}
return assertContent( source.getPropertyValue( propertyName ), context, propertyName );
}
public String assertContent( String response, SubmitContext context, String type ) throws AssertionException
{
try
{
if( path == null )
return "Missing path for XPath assertion";
if( expectedContent == null )
return "Missing content for XPath assertion";
XmlOptions options = new XmlOptions();
if( ignoreComments )
options.setLoadStripComments();
// XmlObject xml = XmlObject.Factory.parse( response, options );
XmlObject xml = XmlUtils.createXmlObject( response, options );
String expandedPath = PropertyExpander.expandProperties( context, path );
XmlObject[] items = xml.selectPath( expandedPath );
AssertedXPathsContainer assertedXPathsContainer = ( AssertedXPathsContainer )context
.getProperty( AssertedXPathsContainer.ASSERTEDXPATHSCONTAINER_PROPERTY );
XmlObject contentObj = null;
String expandedContent = PropertyExpander.expandProperties( context, expectedContent );
// stupid check for text selection for those situation that the
// selected
// text actually contains xml which should be compared as a string.
if( !expandedPath.endsWith( "text()" ) )
{
try
{
// contentObj = XmlObject.Factory.parse( expandedContent, options
// );
contentObj = XmlUtils.createXmlObject( expandedContent, options );
}
catch( Exception e )
{
// this is ok.. it just means that the content to match is not
// xml
// but
// (hopefully) just a string
}
}
if( items.length == 0 )
throw new Exception( "Missing content for xpath [" + path + "] in " + type );
options.setSavePrettyPrint();
options.setSaveOuter();
for( int c = 0; c < items.length; c++ )
{
try
{
AssertedXPathImpl assertedXPathImpl = null;
if( assertedXPathsContainer != null )
{
String xpath = XmlUtils.createAbsoluteXPath( items[c].getDomNode() );
if( xpath != null )
{
XmlObject xmlObj = items[c];
assertedXPathImpl = new AssertedXPathImpl( this, xpath, xmlObj );
assertedXPathsContainer.addAssertedXPath( assertedXPathImpl );
}
}
if( contentObj == null )
{
if( items[c] instanceof XmlAnySimpleType && !( items[c] instanceof XmlQName ) )
{
String value = ( ( XmlAnySimpleType )items[c] ).getStringValue();
String expandedValue = PropertyExpander.expandProperties( context, value );
XMLAssert.assertEquals( expandedContent, expandedValue );
}
else
{
Node domNode = items[c].getDomNode();
switch( domNode.getNodeType() )
{
case Node.ELEMENT_NODE :
String expandedValue = PropertyExpander.expandProperties( context,
XmlUtils.getElementText( ( Element )domNode ) );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
case Node.ATTRIBUTE_NODE :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
default :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
}
}
}
else
{
compareValues( contentObj.xmlText( options ), items[c].xmlText( options ), items[c] );
}
break;
}
catch( Throwable e )
{
if( c == items.length - 1 )
throw e;
}
}
}
catch( Throwable e )
{
String msg = "";
if( e instanceof ComparisonFailure )
{
ComparisonFailure cf = ( ComparisonFailure )e;
String expected = cf.getExpected();
String actual = cf.getActual();
// if( expected.length() > ERROR_LENGTH_LIMIT )
// expected = expected.substring(0, ERROR_LENGTH_LIMIT) + "..";
//
// if( actual.length() > ERROR_LENGTH_LIMIT )
// actual = actual.substring(0, ERROR_LENGTH_LIMIT) + "..";
- msg = "XPathContains comparison failed, expecting [" + expected + "], actual was [" + actual + "]";
+ msg = "XPathContains comparison failed for path [" + path + "], expecting [" + expected + "], actual was [" + actual + "]";
}
else
{
msg = "XPathContains assertion failed for path [" + path + "] : " + e.getClass().getSimpleName() + ":"
+ e.getMessage();
}
throw new AssertionException( new AssertionError( msg ) );
}
return type + " matches content for [" + path + "]";
}
private void compareValues( String expandedContent, String expandedValue, XmlObject object ) throws Exception
{
Diff diff = new Diff( expandedContent, expandedValue );
InternalDifferenceListener internalDifferenceListener = new InternalDifferenceListener();
diff.overrideDifferenceListener( internalDifferenceListener );
if( !diff.identical() )
throw new Exception( diff.toString() );
StringList nodesToRemove = internalDifferenceListener.getNodesToRemove();
if( !nodesToRemove.isEmpty() )
{
for( String node : nodesToRemove )
{
if( node == null )
continue;
int ix = node.indexOf( "\n/" );
if( ix != -1 )
node = node.substring( 0, ix + 1 ) + "./" + node.substring( ix + 1 );
else if( node.startsWith( "/" ) )
node = "/" + node;
XmlObject[] paths = object.selectPath( node );
if( paths.length > 0 )
{
Node domNode = paths[0].getDomNode();
if( domNode.getNodeType() == Node.ATTRIBUTE_NODE )
( ( Attr )domNode ).getOwnerElement().removeAttributeNode( ( Attr )domNode );
else
domNode.getParentNode().removeChild( domNode );
try
{
object.set( object.copy() );
}
catch( XmlValueDisconnectedException e )
{
// this means that we've excluded the root note.. it's ok..
return;
}
}
}
}
}
@Override
public boolean configure()
{
if( configurationDialog == null )
buildConfigurationDialog();
pathArea.setText( path );
contentArea.setText( expectedContent );
allowWildcardsCheckBox.setSelected( allowWildcards );
ignoreNamespaceDifferencesCheckBox.setSelected( ignoreNamespaceDifferences );
UISupport.showDialog( configurationDialog );
return configureResult;
}
protected void buildConfigurationDialog()
{
configurationDialog = new JDialog( UISupport.getMainFrame() );
configurationDialog.setTitle( "XPath Match Configuration" );
configurationDialog.addWindowListener( new WindowAdapter()
{
@Override
public void windowOpened( WindowEvent event )
{
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
// pathArea.requestFocusInWindow();
}
} );
}
} );
JPanel contentPanel = new JPanel( new BorderLayout() );
contentPanel.add( UISupport.buildDescription( "Specify xpath expression and expected result",
"declare namespaces with <code>declare namespace <prefix>='<namespace>';</code>", null ),
BorderLayout.NORTH );
JSplitPane splitPane = UISupport.createVerticalSplit();
pathArea = new JUndoableTextArea();
pathArea.setToolTipText( "Specifies the XPath expression to select from the message for validation" );
JPanel pathPanel = new JPanel( new BorderLayout() );
JXToolBar pathToolbar = UISupport.createToolbar();
addPathEditorActions( pathToolbar );
pathPanel.add( pathToolbar, BorderLayout.NORTH );
pathPanel.add( new JScrollPane( pathArea ), BorderLayout.CENTER );
splitPane.setTopComponent( UISupport.addTitledBorder( pathPanel, "XPath Expression" ) );
contentArea = new JUndoableTextArea();
contentArea.setToolTipText( "Specifies the expected result of the XPath expression" );
JPanel matchPanel = new JPanel( new BorderLayout() );
JXToolBar contentToolbar = UISupport.createToolbar();
addMatchEditorActions( contentToolbar );
matchPanel.add( contentToolbar, BorderLayout.NORTH );
matchPanel.add( new JScrollPane( contentArea ), BorderLayout.CENTER );
splitPane.setBottomComponent( UISupport.addTitledBorder( matchPanel, "Expected Result" ) );
splitPane.setDividerLocation( 150 );
splitPane.setBorder( BorderFactory.createEmptyBorder( 0, 1, 0, 1 ) );
contentPanel.add( splitPane, BorderLayout.CENTER );
ButtonBarBuilder builder = new ButtonBarBuilder();
ShowOnlineHelpAction showOnlineHelpAction = new ShowOnlineHelpAction( HelpUrls.XPATHASSERTIONEDITOR_HELP_URL );
builder.addFixed( UISupport.createToolbarButton( showOnlineHelpAction ) );
builder.addGlue();
JButton okButton = new JButton( new OkAction() );
builder.addFixed( okButton );
builder.addRelatedGap();
builder.addFixed( new JButton( new CancelAction() ) );
builder.setBorder( BorderFactory.createEmptyBorder( 1, 5, 5, 5 ) );
contentPanel.add( builder.getPanel(), BorderLayout.SOUTH );
configurationDialog.setContentPane( contentPanel );
configurationDialog.setSize( 800, 500 );
configurationDialog.setModal( true );
UISupport.initDialogActions( configurationDialog, showOnlineHelpAction, okButton );
}
protected void addPathEditorActions( JXToolBar toolbar )
{
toolbar.addFixed( new JButton( new DeclareNamespacesFromCurrentAction() ) );
}
protected void addMatchEditorActions( JXToolBar toolbar )
{
toolbar.addFixed( new JButton( new SelectFromCurrentAction() ) );
toolbar.addRelatedGap();
toolbar.addFixed( new JButton( new TestPathAction() ) );
allowWildcardsCheckBox = new JCheckBox( "Allow Wildcards" );
Dimension dim = new Dimension( 120, 20 );
allowWildcardsCheckBox.setSize( dim );
allowWildcardsCheckBox.setPreferredSize( dim );
allowWildcardsCheckBox.setOpaque( false );
toolbar.addRelatedGap();
toolbar.addFixed( allowWildcardsCheckBox );
Dimension largerDim = new Dimension( 170, 20 );
ignoreNamespaceDifferencesCheckBox = new JCheckBox( "Ignore namespace prefixes" );
ignoreNamespaceDifferencesCheckBox.setSize( largerDim );
ignoreNamespaceDifferencesCheckBox.setPreferredSize( largerDim );
ignoreNamespaceDifferencesCheckBox.setOpaque( false );
toolbar.addRelatedGap();
toolbar.addFixed( ignoreNamespaceDifferencesCheckBox );
ignoreCommentsCheckBox = new JCheckBox( "Ignore XML Comments" );
ignoreCommentsCheckBox.setSize( largerDim );
ignoreCommentsCheckBox.setPreferredSize( largerDim );
ignoreCommentsCheckBox.setOpaque( false );
toolbar.addRelatedGap();
toolbar.addFixed( ignoreCommentsCheckBox );
}
public XmlObject createConfiguration()
{
XmlObjectConfigurationBuilder builder = new XmlObjectConfigurationBuilder();
builder.add( "path", path );
builder.add( "content", expectedContent );
builder.add( "allowWildcards", allowWildcards );
builder.add( "ignoreNamspaceDifferences", ignoreNamespaceDifferences );
builder.add( "ignoreComments", ignoreComments );
return builder.finish();
}
public void selectFromCurrent()
{
XmlCursor cursor = null;
try
{
String assertableContent = getAssertable().getAssertableContent();
if( assertableContent == null || assertableContent.trim().length() == 0 )
{
UISupport.showErrorMessage( "Missing content to select from" );
return;
}
// XmlObject xml = XmlObject.Factory.parse( assertableContent );
XmlObject xml = XmlUtils.createXmlObject( assertableContent );
String txt = pathArea == null || !pathArea.isVisible() ? getPath() : pathArea.getSelectedText();
if( txt == null )
txt = pathArea == null ? "" : pathArea.getText();
WsdlTestRunContext context = new WsdlTestRunContext( getAssertable().getTestStep() );
String expandedPath = PropertyExpander.expandProperties( context, txt.trim() );
if( contentArea != null && contentArea.isVisible() )
contentArea.setText( "" );
cursor = xml.newCursor();
cursor.selectPath( expandedPath );
if( !cursor.toNextSelection() )
{
UISupport.showErrorMessage( "No match in current response" );
}
else if( cursor.hasNextSelection() )
{
UISupport.showErrorMessage( "More than one match in current response" );
}
else
{
String stringValue = XmlUtils.getValueForMatch( cursor );
if( contentArea != null && contentArea.isVisible() )
contentArea.setText( stringValue );
else
{
setExpectedContent( stringValue, false );
}
}
}
catch( Throwable e )
{
UISupport.showErrorMessage( "Invalid XPath expression." );
SoapUI.logError( e );
}
finally
{
if( cursor != null )
cursor.dispose();
}
}
private void setExpectedContent( String expectedContent, boolean save )
{
this.expectedContent = expectedContent;
if( save )
setConfiguration( createConfiguration() );
}
private final class InternalDifferenceListener implements DifferenceListener
{
private StringList nodesToRemove = new StringList();
public int differenceFound( Difference diff )
{
if( allowWildcards
&& ( diff.getId() == DifferenceEngine.TEXT_VALUE.getId() || diff.getId() == DifferenceEngine.ATTR_VALUE
.getId() ) )
{
if( diff.getControlNodeDetail().getValue().equals( "*" ) )
{
Node node = diff.getTestNodeDetail().getNode();
String xp = XmlUtils.createAbsoluteXPath( node.getNodeType() == Node.ATTRIBUTE_NODE ? node : node
.getParentNode() );
nodesToRemove.add( xp );
return Diff.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
else if( allowWildcards && diff.getId() == DifferenceEngine.NODE_TYPE.getId() )
{
if( diff.getControlNodeDetail().getNode().getNodeValue().equals( "*" ) )
{
Node node = diff.getTestNodeDetail().getNode();
String xp = XmlUtils.createAbsoluteXPath( node.getNodeType() == Node.ATTRIBUTE_NODE ? node : node
.getParentNode() );
nodesToRemove.add( xp );
return Diff.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
}
else if( ignoreNamespaceDifferences && diff.getId() == DifferenceEngine.NAMESPACE_PREFIX_ID )
{
return Diff.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;
}
return Diff.RETURN_ACCEPT_DIFFERENCE;
}
public void skippedComparison( Node arg0, Node arg1 )
{
}
public StringList getNodesToRemove()
{
return nodesToRemove;
}
}
public class OkAction extends AbstractAction
{
public OkAction()
{
super( "Save" );
}
public void actionPerformed( ActionEvent arg0 )
{
setPath( pathArea.getText().trim() );
setExpectedContent( contentArea.getText() );
setAllowWildcards( allowWildcardsCheckBox.isSelected() );
setIgnoreNamespaceDifferences( ignoreNamespaceDifferencesCheckBox.isSelected() );
setIgnoreComments( ignoreCommentsCheckBox.isSelected() );
setConfiguration( createConfiguration() );
configureResult = true;
configurationDialog.setVisible( false );
}
}
public class CancelAction extends AbstractAction
{
public CancelAction()
{
super( "Cancel" );
}
public void actionPerformed( ActionEvent arg0 )
{
configureResult = false;
configurationDialog.setVisible( false );
}
}
public class DeclareNamespacesFromCurrentAction extends AbstractAction
{
public DeclareNamespacesFromCurrentAction()
{
super( "Declare" );
putValue( Action.SHORT_DESCRIPTION, "Add namespace declaration from current message to XPath expression" );
}
public void actionPerformed( ActionEvent arg0 )
{
try
{
String content = getAssertable().getAssertableContent();
if( content != null && content.trim().length() > 0 )
{
pathArea.setText( XmlUtils.declareXPathNamespaces( content ) + pathArea.getText() );
}
else if( UISupport.confirm( "Declare namespaces from schema instead?", "Missing Response" ) )
{
pathArea.setText( XmlUtils.declareXPathNamespaces( ( WsdlInterface )getAssertable().getInterface() )
+ pathArea.getText() );
}
}
catch( Exception e )
{
log.error( e.getMessage() );
}
}
}
public class TestPathAction extends AbstractAction
{
public TestPathAction()
{
super( "Test" );
putValue( Action.SHORT_DESCRIPTION,
"Tests the XPath expression for the current message against the Expected Content field" );
}
public void actionPerformed( ActionEvent arg0 )
{
String oldPath = getPath();
String oldContent = getExpectedContent();
boolean oldAllowWildcards = isAllowWildcards();
setPath( pathArea.getText().trim() );
setExpectedContent( contentArea.getText() );
setAllowWildcards( allowWildcardsCheckBox.isSelected() );
setIgnoreNamespaceDifferences( ignoreNamespaceDifferencesCheckBox.isSelected() );
setIgnoreComments( ignoreCommentsCheckBox.isSelected() );
try
{
String msg = assertContent( getAssertable().getAssertableContent(), new WsdlTestRunContext( getAssertable()
.getTestStep() ), "Response" );
UISupport.showInfoMessage( msg, "Success" );
}
catch( AssertionException e )
{
UISupport.showErrorMessage( e.getMessage() );
}
setPath( oldPath );
setExpectedContent( oldContent );
setAllowWildcards( oldAllowWildcards );
}
}
public class SelectFromCurrentAction extends AbstractAction
{
public SelectFromCurrentAction()
{
super( "Select from current" );
putValue( Action.SHORT_DESCRIPTION,
"Selects the XPath expression from the current message into the Expected Content field" );
}
public void actionPerformed( ActionEvent arg0 )
{
selectFromCurrent();
}
}
@Override
protected String internalAssertRequest( MessageExchange messageExchange, SubmitContext context )
throws AssertionException
{
if( !messageExchange.hasRequest( true ) )
return "Missing Request";
else
return assertContent( messageExchange.getRequestContent(), context, "Request" );
}
public JTextArea getContentArea()
{
return contentArea;
}
public JTextArea getPathArea()
{
return pathArea;
}
@Override
public PropertyExpansion[] getPropertyExpansions()
{
List<PropertyExpansion> result = new ArrayList<PropertyExpansion>();
result.addAll( PropertyExpansionUtils.extractPropertyExpansions( getAssertable().getModelItem(), this,
"expectedContent" ) );
result.addAll( PropertyExpansionUtils.extractPropertyExpansions( getAssertable().getModelItem(), this, "path" ) );
return result.toArray( new PropertyExpansion[result.size()] );
}
public XPathReference[] getXPathReferences()
{
List<XPathReference> result = new ArrayList<XPathReference>();
if( StringUtils.hasContent( getPath() ) )
{
TestModelItem testStep = getAssertable().getTestStep();
TestProperty property = testStep instanceof WsdlTestRequestStep ? testStep.getProperty( "Response" )
: testStep.getProperty( "Request" );
result.add( new XPathReferenceImpl( "XPath for " + getName() + " XPathContainsAssertion in "
+ testStep.getName(), property, this, "path" ) );
}
return result.toArray( new XPathReference[result.size()] );
}
public static class Factory extends AbstractTestAssertionFactory
{
public Factory()
{
super( XPathContainsAssertion.ID, XPathContainsAssertion.LABEL, XPathContainsAssertion.class );
}
@Override
public String getCategory()
{
return AssertionCategoryMapping.VALIDATE_RESPONSE_CONTENT_CATEGORY;
}
@Override
public Class<? extends WsdlMessageAssertion> getAssertionClassType()
{
return XPathContainsAssertion.class;
}
@Override
public AssertionListEntry getAssertionListEntry()
{
return new AssertionListEntry( XPathContainsAssertion.ID, XPathContainsAssertion.LABEL,
XPathContainsAssertion.DESCRIPTION );
}
@Override
public boolean canAssert( TestPropertyHolder modelItem, String property )
{
if( !modelItem.getProperty( property ).getSchemaType().isPrimitiveType() )
return true;
String content = modelItem.getPropertyValue( property );
return XmlUtils.seemsToBeXml( content );
}
}
}
| true | true | public String assertContent( String response, SubmitContext context, String type ) throws AssertionException
{
try
{
if( path == null )
return "Missing path for XPath assertion";
if( expectedContent == null )
return "Missing content for XPath assertion";
XmlOptions options = new XmlOptions();
if( ignoreComments )
options.setLoadStripComments();
// XmlObject xml = XmlObject.Factory.parse( response, options );
XmlObject xml = XmlUtils.createXmlObject( response, options );
String expandedPath = PropertyExpander.expandProperties( context, path );
XmlObject[] items = xml.selectPath( expandedPath );
AssertedXPathsContainer assertedXPathsContainer = ( AssertedXPathsContainer )context
.getProperty( AssertedXPathsContainer.ASSERTEDXPATHSCONTAINER_PROPERTY );
XmlObject contentObj = null;
String expandedContent = PropertyExpander.expandProperties( context, expectedContent );
// stupid check for text selection for those situation that the
// selected
// text actually contains xml which should be compared as a string.
if( !expandedPath.endsWith( "text()" ) )
{
try
{
// contentObj = XmlObject.Factory.parse( expandedContent, options
// );
contentObj = XmlUtils.createXmlObject( expandedContent, options );
}
catch( Exception e )
{
// this is ok.. it just means that the content to match is not
// xml
// but
// (hopefully) just a string
}
}
if( items.length == 0 )
throw new Exception( "Missing content for xpath [" + path + "] in " + type );
options.setSavePrettyPrint();
options.setSaveOuter();
for( int c = 0; c < items.length; c++ )
{
try
{
AssertedXPathImpl assertedXPathImpl = null;
if( assertedXPathsContainer != null )
{
String xpath = XmlUtils.createAbsoluteXPath( items[c].getDomNode() );
if( xpath != null )
{
XmlObject xmlObj = items[c];
assertedXPathImpl = new AssertedXPathImpl( this, xpath, xmlObj );
assertedXPathsContainer.addAssertedXPath( assertedXPathImpl );
}
}
if( contentObj == null )
{
if( items[c] instanceof XmlAnySimpleType && !( items[c] instanceof XmlQName ) )
{
String value = ( ( XmlAnySimpleType )items[c] ).getStringValue();
String expandedValue = PropertyExpander.expandProperties( context, value );
XMLAssert.assertEquals( expandedContent, expandedValue );
}
else
{
Node domNode = items[c].getDomNode();
switch( domNode.getNodeType() )
{
case Node.ELEMENT_NODE :
String expandedValue = PropertyExpander.expandProperties( context,
XmlUtils.getElementText( ( Element )domNode ) );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
case Node.ATTRIBUTE_NODE :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
default :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
}
}
}
else
{
compareValues( contentObj.xmlText( options ), items[c].xmlText( options ), items[c] );
}
break;
}
catch( Throwable e )
{
if( c == items.length - 1 )
throw e;
}
}
}
catch( Throwable e )
{
String msg = "";
if( e instanceof ComparisonFailure )
{
ComparisonFailure cf = ( ComparisonFailure )e;
String expected = cf.getExpected();
String actual = cf.getActual();
// if( expected.length() > ERROR_LENGTH_LIMIT )
// expected = expected.substring(0, ERROR_LENGTH_LIMIT) + "..";
//
// if( actual.length() > ERROR_LENGTH_LIMIT )
// actual = actual.substring(0, ERROR_LENGTH_LIMIT) + "..";
msg = "XPathContains comparison failed, expecting [" + expected + "], actual was [" + actual + "]";
}
else
{
msg = "XPathContains assertion failed for path [" + path + "] : " + e.getClass().getSimpleName() + ":"
+ e.getMessage();
}
throw new AssertionException( new AssertionError( msg ) );
}
return type + " matches content for [" + path + "]";
}
| public String assertContent( String response, SubmitContext context, String type ) throws AssertionException
{
try
{
if( path == null )
return "Missing path for XPath assertion";
if( expectedContent == null )
return "Missing content for XPath assertion";
XmlOptions options = new XmlOptions();
if( ignoreComments )
options.setLoadStripComments();
// XmlObject xml = XmlObject.Factory.parse( response, options );
XmlObject xml = XmlUtils.createXmlObject( response, options );
String expandedPath = PropertyExpander.expandProperties( context, path );
XmlObject[] items = xml.selectPath( expandedPath );
AssertedXPathsContainer assertedXPathsContainer = ( AssertedXPathsContainer )context
.getProperty( AssertedXPathsContainer.ASSERTEDXPATHSCONTAINER_PROPERTY );
XmlObject contentObj = null;
String expandedContent = PropertyExpander.expandProperties( context, expectedContent );
// stupid check for text selection for those situation that the
// selected
// text actually contains xml which should be compared as a string.
if( !expandedPath.endsWith( "text()" ) )
{
try
{
// contentObj = XmlObject.Factory.parse( expandedContent, options
// );
contentObj = XmlUtils.createXmlObject( expandedContent, options );
}
catch( Exception e )
{
// this is ok.. it just means that the content to match is not
// xml
// but
// (hopefully) just a string
}
}
if( items.length == 0 )
throw new Exception( "Missing content for xpath [" + path + "] in " + type );
options.setSavePrettyPrint();
options.setSaveOuter();
for( int c = 0; c < items.length; c++ )
{
try
{
AssertedXPathImpl assertedXPathImpl = null;
if( assertedXPathsContainer != null )
{
String xpath = XmlUtils.createAbsoluteXPath( items[c].getDomNode() );
if( xpath != null )
{
XmlObject xmlObj = items[c];
assertedXPathImpl = new AssertedXPathImpl( this, xpath, xmlObj );
assertedXPathsContainer.addAssertedXPath( assertedXPathImpl );
}
}
if( contentObj == null )
{
if( items[c] instanceof XmlAnySimpleType && !( items[c] instanceof XmlQName ) )
{
String value = ( ( XmlAnySimpleType )items[c] ).getStringValue();
String expandedValue = PropertyExpander.expandProperties( context, value );
XMLAssert.assertEquals( expandedContent, expandedValue );
}
else
{
Node domNode = items[c].getDomNode();
switch( domNode.getNodeType() )
{
case Node.ELEMENT_NODE :
String expandedValue = PropertyExpander.expandProperties( context,
XmlUtils.getElementText( ( Element )domNode ) );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
case Node.ATTRIBUTE_NODE :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
if( allowWildcards )
Tools.assertSimilar( expandedContent, expandedValue, '*' );
else
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
default :
expandedValue = PropertyExpander.expandProperties( context, domNode.getNodeValue() );
XMLAssert.assertEquals( expandedContent, expandedValue );
break;
}
}
}
else
{
compareValues( contentObj.xmlText( options ), items[c].xmlText( options ), items[c] );
}
break;
}
catch( Throwable e )
{
if( c == items.length - 1 )
throw e;
}
}
}
catch( Throwable e )
{
String msg = "";
if( e instanceof ComparisonFailure )
{
ComparisonFailure cf = ( ComparisonFailure )e;
String expected = cf.getExpected();
String actual = cf.getActual();
// if( expected.length() > ERROR_LENGTH_LIMIT )
// expected = expected.substring(0, ERROR_LENGTH_LIMIT) + "..";
//
// if( actual.length() > ERROR_LENGTH_LIMIT )
// actual = actual.substring(0, ERROR_LENGTH_LIMIT) + "..";
msg = "XPathContains comparison failed for path [" + path + "], expecting [" + expected + "], actual was [" + actual + "]";
}
else
{
msg = "XPathContains assertion failed for path [" + path + "] : " + e.getClass().getSimpleName() + ":"
+ e.getMessage();
}
throw new AssertionException( new AssertionError( msg ) );
}
return type + " matches content for [" + path + "]";
}
|
diff --git a/trunk/src/java/org/apache/commons/dbcp2/managed/ManagedDataSource.java b/trunk/src/java/org/apache/commons/dbcp2/managed/ManagedDataSource.java
index f50bd11..0b38ad8 100644
--- a/trunk/src/java/org/apache/commons/dbcp2/managed/ManagedDataSource.java
+++ b/trunk/src/java/org/apache/commons/dbcp2/managed/ManagedDataSource.java
@@ -1,82 +1,82 @@
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.dbcp2.managed;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.dbcp2.PoolingDataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* The ManagedDataSource is a PoolingDataSource that creates ManagedConnections.
*
* @author Dain Sundstrom
* @version $Revision$
*/
public class ManagedDataSource<C extends Connection> extends PoolingDataSource<C> {
private TransactionRegistry transactionRegistry;
/**
* Creates an uninitialized datasource. Before this data source can be used a pool and
* transaction registry must be set.
*/
public ManagedDataSource() {
}
/**
* Creates a ManagedDataSource which obtains connections from the specified pool and
* manages them using the specified transaction registry. The TransactionRegistry must
* be the transaction registry obtained from the XAConnectionFactory used to create
* the connection pool. If not an error will occure when attempting to use the connection
* in a global transaction because the XAResource object associated with the connection
* will be unavailable.
*
* @param pool the connection pool
* @param transactionRegistry the transaction registry obtained from the
* XAConnectionFactory used to create the connection pool object factory
*/
public ManagedDataSource(ObjectPool<C> pool,
TransactionRegistry transactionRegistry) {
super(pool);
this.transactionRegistry = transactionRegistry;
}
/**
* Sets the transaction registry from the XAConnectionFactory used to create the pool.
* The transaction registry can only be set once using either a connector or this setter
* method.
* @param transactionRegistry the transaction registry acquired from the XAConnectionFactory
* used to create the pool
*/
public void setTransactionRegistry(TransactionRegistry transactionRegistry) {
if(this.transactionRegistry != null) throw new IllegalStateException("TransactionRegistry already set");
if(transactionRegistry == null) throw new NullPointerException("TransactionRegistry is null");
this.transactionRegistry = transactionRegistry;
}
@Override
public Connection getConnection() throws SQLException {
if (_pool == null) throw new IllegalStateException("Pool has not been set");
if (transactionRegistry == null) throw new IllegalStateException("TransactionRegistry has not been set");
- Connection connection = new ManagedConnection(_pool, transactionRegistry, isAccessToUnderlyingConnectionAllowed());
+ Connection connection = new ManagedConnection<>(_pool, transactionRegistry, isAccessToUnderlyingConnectionAllowed());
return connection;
}
}
| true | true | public Connection getConnection() throws SQLException {
if (_pool == null) throw new IllegalStateException("Pool has not been set");
if (transactionRegistry == null) throw new IllegalStateException("TransactionRegistry has not been set");
Connection connection = new ManagedConnection(_pool, transactionRegistry, isAccessToUnderlyingConnectionAllowed());
return connection;
}
| public Connection getConnection() throws SQLException {
if (_pool == null) throw new IllegalStateException("Pool has not been set");
if (transactionRegistry == null) throw new IllegalStateException("TransactionRegistry has not been set");
Connection connection = new ManagedConnection<>(_pool, transactionRegistry, isAccessToUnderlyingConnectionAllowed());
return connection;
}
|
diff --git a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/CreateFolderDialogPresenter.java b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/CreateFolderDialogPresenter.java
index 23f45a8a6..8cf8d0d61 100644
--- a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/CreateFolderDialogPresenter.java
+++ b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/fs/presenter/CreateFolderDialogPresenter.java
@@ -1,149 +1,153 @@
/*******************************************************************************
* Copyright 2008(c) The OBiBa Consortium. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.opal.web.gwt.app.client.fs.presenter;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.Place;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
import org.obiba.opal.web.gwt.app.client.event.UserMessageEvent;
import org.obiba.opal.web.gwt.app.client.i18n.Translations;
import org.obiba.opal.web.gwt.app.client.presenter.ErrorDialogPresenter.MessageDialogType;
import org.obiba.opal.web.gwt.app.client.widgets.event.FolderCreationEvent;
import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory;
import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback;
import org.obiba.opal.web.model.client.FileDto;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.HasCloseHandlers;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
public class CreateFolderDialogPresenter extends WidgetPresenter<CreateFolderDialogPresenter.Display> {
public interface Display extends WidgetDisplay {
void showDialog();
void hideDialog();
HasClickHandlers getCreateFolderButton();
HasClickHandlers getCancelButton();
HasText getFolderToCreate();
HasText getErrorMsg();
HasCloseHandlers<DialogBox> getDialog();
}
private Translations translations = GWT.create(Translations.class);
private FileDto currentFolder;
@Inject
public CreateFolderDialogPresenter(Display display, EventBus eventBus) {
super(display, eventBus);
}
@Override
public Place getPlace() {
return null;
}
@Override
protected void onBind() {
initDisplayComponents();
addEventHandlers();
}
@Override
protected void onPlaceRequest(PlaceRequest request) {
}
@Override
protected void onUnbind() {
}
@Override
public void refreshDisplay() {
}
@Override
public void revealDisplay() {
initDisplayComponents();
getDisplay().showDialog();
}
protected void initDisplayComponents() {
getDisplay().getFolderToCreate().setText("");
getDisplay().getErrorMsg().setText("");
}
private void addEventHandlers() {
super.registerHandler(getDisplay().getCreateFolderButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String folderToCreate = getDisplay().getFolderToCreate().getText();
if(folderToCreate.equals("")) {
getDisplay().getErrorMsg().setText(translations.folderNameIsRequired());
} else {
- createFolder(currentFolder.getPath() + "/" + folderToCreate);
+ if(currentFolder.getPath().equals("/")) { // create under root
+ createFolder("/" + folderToCreate);
+ } else {
+ createFolder(currentFolder.getPath() + "/" + folderToCreate);
+ }
}
}
}));
super.registerHandler(getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
getDisplay().hideDialog();
}
}));
getDisplay().getDialog().addCloseHandler(new CloseHandler<DialogBox>() {
@Override
public void onClose(CloseEvent<DialogBox> event) {
unbind();
}
});
}
private void createFolder(final String folder) {
ResponseCodeCallback callbackHandler = new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if(response.getStatusCode() == 201) {
eventBus.fireEvent(new FolderCreationEvent(folder));
getDisplay().hideDialog();
} else {
GWT.log(response.getText());
eventBus.fireEvent(new UserMessageEvent(MessageDialogType.ERROR, response.getText(), null));
}
}
};
ResourceRequestBuilderFactory.newBuilder().forResource("/files" + folder).put().withCallback(201, callbackHandler).withCallback(403, callbackHandler).withCallback(500, callbackHandler).send();
}
public void setCurrentFolder(FileDto currentFolder) {
this.currentFolder = currentFolder;
}
}
| true | true | private void addEventHandlers() {
super.registerHandler(getDisplay().getCreateFolderButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String folderToCreate = getDisplay().getFolderToCreate().getText();
if(folderToCreate.equals("")) {
getDisplay().getErrorMsg().setText(translations.folderNameIsRequired());
} else {
createFolder(currentFolder.getPath() + "/" + folderToCreate);
}
}
}));
super.registerHandler(getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
getDisplay().hideDialog();
}
}));
getDisplay().getDialog().addCloseHandler(new CloseHandler<DialogBox>() {
@Override
public void onClose(CloseEvent<DialogBox> event) {
unbind();
}
});
}
| private void addEventHandlers() {
super.registerHandler(getDisplay().getCreateFolderButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String folderToCreate = getDisplay().getFolderToCreate().getText();
if(folderToCreate.equals("")) {
getDisplay().getErrorMsg().setText(translations.folderNameIsRequired());
} else {
if(currentFolder.getPath().equals("/")) { // create under root
createFolder("/" + folderToCreate);
} else {
createFolder(currentFolder.getPath() + "/" + folderToCreate);
}
}
}
}));
super.registerHandler(getDisplay().getCancelButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
getDisplay().hideDialog();
}
}));
getDisplay().getDialog().addCloseHandler(new CloseHandler<DialogBox>() {
@Override
public void onClose(CloseEvent<DialogBox> event) {
unbind();
}
});
}
|
diff --git a/src/main/java/ditl/StatefulReader.java b/src/main/java/ditl/StatefulReader.java
index 1284cf2..44caea8 100644
--- a/src/main/java/ditl/StatefulReader.java
+++ b/src/main/java/ditl/StatefulReader.java
@@ -1,82 +1,82 @@
/*******************************************************************************
* This file is part of DITL. *
* *
* Copyright (C) 2011-2012 John Whitbeck <[email protected]> *
* *
* DITL is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* DITL is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************/
package ditl;
import java.io.IOException;
import java.util.Set;
public class StatefulReader<E extends Item, S extends Item> extends Reader<E> {
private final StateUpdater<E, S> _updater;
private Bus<S> state_bus = new Bus<S>();
private final Item.Factory<S> state_factory;
StatefulReader(StatefulTrace<E, S> trace, int priority, long offset) throws IOException {
super(trace, priority, offset);
_updater = trace.getNewUpdaterFactory();
state_factory = trace.stateFactory();
}
public Set<S> referenceState() {
return _updater.states();
}
@Override
public void seek(long time) throws IOException {
if (seek_map.getOffset(time + _offset) == Long.MIN_VALUE) {
throw new IOException("Cannot seek before initial state");
}
fastSeek(time + _offset);
// we always hit a state item block after this step
_updater.setState(readItemBlock(state_factory));
prev_time = next_time;
readHeader();
- while (hasNext() && nextTime() < time + _offset) {
+ while (hasNext() && next_time < time + _offset) {
for (final E event : next()) {
// cur_time is updated by call to next
_updater.handleEvent(cur_time, event);
}
}
state_bus.queue(time, _updater.states());
cur_time = time + _offset;
}
public void setStateBus(Bus<S> bus) {
state_bus = bus;
}
public Bus<S> stateBus() {
return state_bus;
}
@Override
public void step() throws IOException {
if (next_flag == StatefulWriter.STATE) {
skipBlock();
readHeader();
}
super.step();
}
@Override
public Bus<?>[] busses() {
return new Bus<?>[] { _bus, state_bus };
}
}
| true | true | public void seek(long time) throws IOException {
if (seek_map.getOffset(time + _offset) == Long.MIN_VALUE) {
throw new IOException("Cannot seek before initial state");
}
fastSeek(time + _offset);
// we always hit a state item block after this step
_updater.setState(readItemBlock(state_factory));
prev_time = next_time;
readHeader();
while (hasNext() && nextTime() < time + _offset) {
for (final E event : next()) {
// cur_time is updated by call to next
_updater.handleEvent(cur_time, event);
}
}
state_bus.queue(time, _updater.states());
cur_time = time + _offset;
}
| public void seek(long time) throws IOException {
if (seek_map.getOffset(time + _offset) == Long.MIN_VALUE) {
throw new IOException("Cannot seek before initial state");
}
fastSeek(time + _offset);
// we always hit a state item block after this step
_updater.setState(readItemBlock(state_factory));
prev_time = next_time;
readHeader();
while (hasNext() && next_time < time + _offset) {
for (final E event : next()) {
// cur_time is updated by call to next
_updater.handleEvent(cur_time, event);
}
}
state_bus.queue(time, _updater.states());
cur_time = time + _offset;
}
|
diff --git a/src/main/java/com/pahimar/ee3/handler/FuelHandler.java b/src/main/java/com/pahimar/ee3/handler/FuelHandler.java
index 10d6c306..a91a1071 100644
--- a/src/main/java/com/pahimar/ee3/handler/FuelHandler.java
+++ b/src/main/java/com/pahimar/ee3/handler/FuelHandler.java
@@ -1,59 +1,59 @@
package com.pahimar.ee3.handler;
import com.pahimar.ee3.block.ModBlocks;
import com.pahimar.ee3.item.ModItems;
import cpw.mods.fml.common.IFuelHandler;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntityFurnace;
public class FuelHandler implements IFuelHandler
{
private static final ItemStack ALCHEMICAL_COAL_STACK = new ItemStack(ModItems.alchemicalFuel, 1, 0);
private static final ItemStack MOBIUS_FUEL_STACK = new ItemStack(ModItems.alchemicalFuel, 1, 1);
private static final ItemStack AETERNALIS_FUEL_STACK = new ItemStack(ModItems.alchemicalFuel, 1, 2);
private static final ItemStack ALCHEMICAL_COAL_BLOCK_STACK = new ItemStack(ModBlocks.alchemicalFuel, 1, 0);
private static final ItemStack MOBIUS_FUEL_BLOCK_STACK = new ItemStack(ModBlocks.alchemicalFuel, 1, 1);
private static final ItemStack AETERNALIS_FUEL_BLOCK_STACK = new ItemStack(ModBlocks.alchemicalFuel, 1, 2);
@Override
public int getBurnTime(ItemStack fuel)
{
/**
* Alchemical Coal
*/
if (fuel.itemID == ALCHEMICAL_COAL_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_STACK.getItemDamage())
{
return 8 * TileEntityFurnace.getItemBurnTime(new ItemStack(Item.coal));
}
else if (fuel.itemID == ALCHEMICAL_COAL_BLOCK_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(ALCHEMICAL_COAL_STACK);
}
/**
* Mobius Fuel
*/
else if (fuel.itemID == MOBIUS_FUEL_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_STACK.getItemDamage())
{
- return 8 * getBurnTime(ALCHEMICAL_COAL_BLOCK_STACK);
+ return 8 * getBurnTime(ALCHEMICAL_COAL_STACK);
}
else if (fuel.itemID == MOBIUS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(MOBIUS_FUEL_STACK);
}
/**
* Aeternalis Fuel
*/
else if (fuel.itemID == AETERNALIS_FUEL_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_STACK.getItemDamage())
{
- return 8 * getBurnTime(new ItemStack(ModItems.alchemicalFuelBlock.itemID, 1, 1));
+ return 8 * getBurnTime(MOBIUS_FUEL_STACK);
}
else if (fuel.itemID == AETERNALIS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(AETERNALIS_FUEL_STACK);
}
return 0;
}
}
| false | true | public int getBurnTime(ItemStack fuel)
{
/**
* Alchemical Coal
*/
if (fuel.itemID == ALCHEMICAL_COAL_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_STACK.getItemDamage())
{
return 8 * TileEntityFurnace.getItemBurnTime(new ItemStack(Item.coal));
}
else if (fuel.itemID == ALCHEMICAL_COAL_BLOCK_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(ALCHEMICAL_COAL_STACK);
}
/**
* Mobius Fuel
*/
else if (fuel.itemID == MOBIUS_FUEL_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_STACK.getItemDamage())
{
return 8 * getBurnTime(ALCHEMICAL_COAL_BLOCK_STACK);
}
else if (fuel.itemID == MOBIUS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(MOBIUS_FUEL_STACK);
}
/**
* Aeternalis Fuel
*/
else if (fuel.itemID == AETERNALIS_FUEL_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_STACK.getItemDamage())
{
return 8 * getBurnTime(new ItemStack(ModItems.alchemicalFuelBlock.itemID, 1, 1));
}
else if (fuel.itemID == AETERNALIS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(AETERNALIS_FUEL_STACK);
}
return 0;
}
| public int getBurnTime(ItemStack fuel)
{
/**
* Alchemical Coal
*/
if (fuel.itemID == ALCHEMICAL_COAL_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_STACK.getItemDamage())
{
return 8 * TileEntityFurnace.getItemBurnTime(new ItemStack(Item.coal));
}
else if (fuel.itemID == ALCHEMICAL_COAL_BLOCK_STACK.itemID && fuel.getItemDamage() == ALCHEMICAL_COAL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(ALCHEMICAL_COAL_STACK);
}
/**
* Mobius Fuel
*/
else if (fuel.itemID == MOBIUS_FUEL_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_STACK.getItemDamage())
{
return 8 * getBurnTime(ALCHEMICAL_COAL_STACK);
}
else if (fuel.itemID == MOBIUS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == MOBIUS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(MOBIUS_FUEL_STACK);
}
/**
* Aeternalis Fuel
*/
else if (fuel.itemID == AETERNALIS_FUEL_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_STACK.getItemDamage())
{
return 8 * getBurnTime(MOBIUS_FUEL_STACK);
}
else if (fuel.itemID == AETERNALIS_FUEL_BLOCK_STACK.itemID && fuel.getItemDamage() == AETERNALIS_FUEL_BLOCK_STACK.getItemDamage())
{
return 9 * getBurnTime(AETERNALIS_FUEL_STACK);
}
return 0;
}
|
diff --git a/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java b/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java
index 5c954a64d..f9584e5d8 100644
--- a/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java
+++ b/dspace/src/org/dspace/app/webui/jsptag/ItemListTag.java
@@ -1,301 +1,303 @@
/*
* ItemListTag.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2001, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.webui.jsptag;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.http.HttpServletRequest;
import org.dspace.app.webui.util.UIUtil;
import org.dspace.content.DCDate;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.handle.HandleManager;
/**
* Tag for display a list of items
*
* @author Robert Tansley
* @version $Revision$
*/
public class ItemListTag extends TagSupport
{
/** Items to display */
private Item[] items;
/** Corresponding handles */
private String[] handles;
/** Row to highlight, -1 for no row */
private int highlightRow;
/** Column to emphasise - null, "title" or "date" */
private String emphColumn;
public ItemListTag()
{
super();
}
public int doStartTag()
throws JspException
{
JspWriter out = pageContext.getOut();
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
try
{
out.println("<table align=center class=\"miscTable\">");
// Row: toggles between Odd and Even
String row = "odd";
for (int i = 0; i < items.length; i++)
{
// Title - we just use the first one
DCValue[] titleArray = items[i].getDC("title", null, Item.ANY);
String title = "Untitled";
if (titleArray.length > 0)
{
title = titleArray[0].value;
}
// Authors....
DCValue[] authors = items[i].getDC("contributor",
"author",
Item.ANY);
// Date issued
DCValue[] dateIssued = items[i].getDC("date",
"issued",
Item.ANY);
DCDate dd = null;
if(dateIssued.length > 0)
{
dd = new DCDate(dateIssued[0].value);
}
// First column is date
out.print("<tr><td nowrap class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowOddCol\" align=right>");
if (emphasiseDate)
{
out.print("<strong>");
}
out.print(UIUtil.displayDate(dd, false, false));
if (emphasiseDate)
{
out.print("</strong>");
}
// Second column is title
out.print("</td><td class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowEvenCol\">");
if (emphasiseTitle)
{
out.print("<strong>");
}
out.print("<A HREF=\"item/");
out.print(handles[i]);
out.print("\">");
out.print(title);
out.print("</A>");
if (emphasiseTitle)
{
out.print("</strong>");
}
// Third column is authors
- out.print("</td><td class=\"" + row + "RowOddCol\">");
+ out.print("</td><td class=\"");
+ out.print(i == highlightRow ? "highlight" : row);
+ out.print("RowOddCol\">");
for (int j = 0; j < authors.length; j++)
{
out.print("<em>" + authors[j].value + "</em>");
if (j < authors.length - 1)
{
out.print("; ");
}
}
out.println("</td></tr>");
row = (row.equals("odd") ? "even" : "odd");
}
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
/**
* Get the items to list
*
* @return the items
*/
public List getItems()
{
return Arrays.asList(items);
}
/**
* Set the items to list
*
* @param itemsIn the items
*/
public void setItems(List itemsIn)
{
items = new Item[itemsIn.size()];
items = (Item[]) itemsIn.toArray(items);
}
/**
* Get the corresponding handles
*
* @return the handles
*/
public String[] getHandles()
{
return handles;
}
/**
* Set the handles corresponding to items
*
* @param handlesIn the handles
*/
public void setHandles(String[] handlesIn)
{
handles = handlesIn;
}
/**
* Get the row to highlight - null or -1 for no row
*
* @return the row to highlight
*/
public String getHighlightrow()
{
return String.valueOf(highlightRow);
}
/**
* Set the row to highlight
*
* @param highlightRowIn the row to highlight or -1 for no highlight
*/
public void setHighlightrow(String highlightRowIn)
{
if (highlightRowIn == null)
{
highlightRow = -1;
}
else
{
try
{
highlightRow = Integer.parseInt(highlightRowIn);
}
catch(NumberFormatException nfe)
{
highlightRow = -1;
}
}
}
/**
* Get the column to emphasise - "title", "date" or null
*
* @return the column to emphasise
*/
public String getEmphcolumn()
{
return emphColumn;
}
/**
* Set the column to emphasise - "title", "date" or null
*
* @param emphcolumnIn column to emphasise
*/
public void setEmphcolumn(String emphColumnIn)
{
emphColumn = emphColumnIn;
}
}
| true | true | public int doStartTag()
throws JspException
{
JspWriter out = pageContext.getOut();
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
try
{
out.println("<table align=center class=\"miscTable\">");
// Row: toggles between Odd and Even
String row = "odd";
for (int i = 0; i < items.length; i++)
{
// Title - we just use the first one
DCValue[] titleArray = items[i].getDC("title", null, Item.ANY);
String title = "Untitled";
if (titleArray.length > 0)
{
title = titleArray[0].value;
}
// Authors....
DCValue[] authors = items[i].getDC("contributor",
"author",
Item.ANY);
// Date issued
DCValue[] dateIssued = items[i].getDC("date",
"issued",
Item.ANY);
DCDate dd = null;
if(dateIssued.length > 0)
{
dd = new DCDate(dateIssued[0].value);
}
// First column is date
out.print("<tr><td nowrap class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowOddCol\" align=right>");
if (emphasiseDate)
{
out.print("<strong>");
}
out.print(UIUtil.displayDate(dd, false, false));
if (emphasiseDate)
{
out.print("</strong>");
}
// Second column is title
out.print("</td><td class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowEvenCol\">");
if (emphasiseTitle)
{
out.print("<strong>");
}
out.print("<A HREF=\"item/");
out.print(handles[i]);
out.print("\">");
out.print(title);
out.print("</A>");
if (emphasiseTitle)
{
out.print("</strong>");
}
// Third column is authors
out.print("</td><td class=\"" + row + "RowOddCol\">");
for (int j = 0; j < authors.length; j++)
{
out.print("<em>" + authors[j].value + "</em>");
if (j < authors.length - 1)
{
out.print("; ");
}
}
out.println("</td></tr>");
row = (row.equals("odd") ? "even" : "odd");
}
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
| public int doStartTag()
throws JspException
{
JspWriter out = pageContext.getOut();
boolean emphasiseDate = false;
boolean emphasiseTitle = false;
if (emphColumn != null)
{
emphasiseDate = emphColumn.equalsIgnoreCase("date");
emphasiseTitle = emphColumn.equalsIgnoreCase("title");
}
try
{
out.println("<table align=center class=\"miscTable\">");
// Row: toggles between Odd and Even
String row = "odd";
for (int i = 0; i < items.length; i++)
{
// Title - we just use the first one
DCValue[] titleArray = items[i].getDC("title", null, Item.ANY);
String title = "Untitled";
if (titleArray.length > 0)
{
title = titleArray[0].value;
}
// Authors....
DCValue[] authors = items[i].getDC("contributor",
"author",
Item.ANY);
// Date issued
DCValue[] dateIssued = items[i].getDC("date",
"issued",
Item.ANY);
DCDate dd = null;
if(dateIssued.length > 0)
{
dd = new DCDate(dateIssued[0].value);
}
// First column is date
out.print("<tr><td nowrap class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowOddCol\" align=right>");
if (emphasiseDate)
{
out.print("<strong>");
}
out.print(UIUtil.displayDate(dd, false, false));
if (emphasiseDate)
{
out.print("</strong>");
}
// Second column is title
out.print("</td><td class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowEvenCol\">");
if (emphasiseTitle)
{
out.print("<strong>");
}
out.print("<A HREF=\"item/");
out.print(handles[i]);
out.print("\">");
out.print(title);
out.print("</A>");
if (emphasiseTitle)
{
out.print("</strong>");
}
// Third column is authors
out.print("</td><td class=\"");
out.print(i == highlightRow ? "highlight" : row);
out.print("RowOddCol\">");
for (int j = 0; j < authors.length; j++)
{
out.print("<em>" + authors[j].value + "</em>");
if (j < authors.length - 1)
{
out.print("; ");
}
}
out.println("</td></tr>");
row = (row.equals("odd") ? "even" : "odd");
}
out.println("</table>");
}
catch (IOException ie)
{
throw new JspException(ie);
}
return SKIP_BODY;
}
|
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/EditableListWidget.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/EditableListWidget.java
index d3b2c98..faa0c67 100644
--- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/EditableListWidget.java
+++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/utils/EditableListWidget.java
@@ -1,679 +1,688 @@
/*******************************************************************************
* Copyright (c) 2011 Ericsson Research Canada
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Description:
*
* This class implements an editable List-like widget
*
* Contributors:
* Sebastien Dubois - Created for Mylyn Review R4E project
*
******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.internal.utils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EParticipant;
import org.eclipse.mylyn.reviews.r4e.ui.R4EUIPlugin;
import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.IParticipantInputDialog;
import org.eclipse.mylyn.reviews.r4e.ui.internal.dialogs.R4EUIDialogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
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.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
/**
* @author lmcdubo
* @version $Revision: 1.0 $
*/
public class EditableListWidget {
// ------------------------------------------------------------------------
// Member variables
// ------------------------------------------------------------------------
/**
* Field fMainComposite.
*/
protected Composite fMainComposite = null;
/**
* Field fMainTable.
*/
protected Table fMainTable = null;
/**
* Field fAddButton.
*/
protected Button fAddButton = null;
/**
* Field fRemoveButton.
*/
protected Button fRemoveButton = null;
/**
* Field fListener.
*/
protected IEditableListListener fListener = null;
/**
* Field fInstanceId.
*/
protected int fInstanceId = 0;
/**
* Field fValues.
*/
protected String[] fValues = null;
/**
* Field fEditableControl.
*/
Control fEditableControl = null;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
//TODO: This should be made more generic to accept various tables. Right now it is very hard-coded to our stuff...
/**
* Constructor for EditableListWidget.
*
* @param aToolkit
* - FormToolkit
* @param aParent
* - Composite
* @param aLayoutData
* - Object
* @param aListener
* - IEditableListListener
* @param aInstanceId
* - int
* @param aEditableWidgetClass
* - Class<?>
* @param aEditableValues
* - String[]
*/
public EditableListWidget(FormToolkit aToolkit, Composite aParent, Object aLayoutData,
IEditableListListener aListener, int aInstanceId, Class<?> aEditableWidgetClass, String[] aEditableValues) {
fMainComposite = (null != aToolkit) ? aToolkit.createComposite(aParent) : new Composite(aParent, SWT.NONE);
fMainComposite.setLayoutData(aLayoutData);
fMainComposite.setLayout(new GridLayout(4, false));
fListener = aListener;
fInstanceId = aInstanceId;
fValues = aEditableValues;
createEditableListFromTable(aToolkit, aEditableWidgetClass);
}
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method dispose.
*/
public void dispose() {
fMainTable.dispose();
fMainComposite.dispose();
}
/**
* Method createEditableListFromTable. Builds the editable list in the provided table
*
* @param aToolkit
* - FormToolkit
* @param aEditableWidgetClass
* - Class<?>
*/
public void createEditableListFromTable(FormToolkit aToolkit, final Class<?> aEditableWidgetClass) {
final Composite tableComposite = (null != aToolkit) ? aToolkit.createComposite(fMainComposite) : new Composite(
fMainComposite, SWT.NONE);
fMainTable = (null != aToolkit)
? aToolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.BORDER)
: new Table(tableComposite, SWT.FULL_SELECTION | SWT.BORDER);
final GridData tableCompositeData = new GridData(GridData.FILL, GridData.FILL, true, true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
tableCompositeData.horizontalSpan = 1;
} else {
tableCompositeData.horizontalSpan = 2;
}
final TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
final TableColumn tableColumn = new TableColumn(fMainTable, SWT.NONE, 0);
final TableColumn tableColumn2;
fMainTable.setLinesVisible(true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
fMainTable.setHeaderVisible(true);
tableColumn2 = new TableColumn(fMainTable, SWT.NONE, 1);
if (aEditableWidgetClass.equals(Date.class)) {
tableColumn.setText(R4EUIConstants.SPENT_TIME_COLUMN_HEADER);
tableColumn2.setText(R4EUIConstants.ENTRY_TIME_COLUMN_HEADER);
} else if (aEditableWidgetClass.equals(Label.class)) {
tableColumn.setText(R4EUIConstants.ID_LABEL);
tableColumn2.setText(R4EUIConstants.EMAIL_LABEL);
}
tableColumn.pack();
tableColumn2.pack();
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(50, tableColumn.getWidth() * 2, true));
tableColumnLayout.setColumnData(tableColumn2, new ColumnWeightData(50, tableColumn.getWidth(), true));
} else {
tableColumn2 = null; //only 1 column
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(10, 100, true));
}
tableComposite.setLayoutData(tableCompositeData);
fMainComposite.addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
//TODO: This does not work 100% as resizing the colums lags when the parent area gets shrinked quickly.
// This causes the rightmost part of the table composite to be clipped away.
// This will need to be improved, see bug 356857.
final Rectangle area = fMainTable.getClientArea();
final Point size = tableComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
final ScrollBar vBar = fMainTable.getVerticalBar();
final int vBarWidth = vBar.getSize().x;
int width = area.width - vBarWidth * 3;
if (width < 0) {
return;
}
if (size.y > area.height + fMainTable.getHeaderHeight()) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
width -= vBarWidth;
}
// Set column width first and then resize the table to
// match the client area width
if (null != tableColumn2) {
tableColumn.setWidth(width / 2);
tableColumn2.setWidth(width - tableColumn.getWidth());
} else {
tableColumn.setWidth(width);
}
}
public void controlMoved(ControlEvent e) {
// ignor
}
});
fMainTable.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent e) {
//Do nothing
}
});
fMainTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
fListener.itemSelected(fMainTable.getSelection()[0], fInstanceId); //Only 1 element selected at any given time
}
});
final Composite buttonsComposite = (null != aToolkit)
? aToolkit.createComposite(fMainComposite)
: new Composite(fMainComposite, SWT.NONE);
buttonsComposite.setLayout(new GridLayout());
buttonsComposite.setLayoutData(new GridData(GridData.CENTER, SWT.TOP, false, false));
fAddButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite, R4EUIConstants.BUTTON_ADD_LABEL,
SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fAddButton.setText(R4EUIConstants.BUTTON_ADD_LABEL);
if (aEditableWidgetClass.equals(CCombo.class)) {
if (null == fValues || 0 == fValues.length) {
fAddButton.setEnabled(false);
}
}
fRemoveButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite,
R4EUIConstants.BUTTON_REMOVE_LABEL, SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fRemoveButton.setText(R4EUIConstants.BUTTON_REMOVE_LABEL);
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
fAddButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fAddButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (aEditableWidgetClass.equals(Label.class)) {
final IParticipantInputDialog dialog = R4EUIDialogFactory.getInstance().getParticipantInputDialog(
false);
final int result = dialog.open();
if (result == Window.OK) {
TableItem newItem = null;
for (R4EParticipant participant : dialog.getParticipants()) {
newItem = null;
String[] tableStrs = new String[2];
tableStrs[0] = participant.getId();
tableStrs[1] = participant.getEmail();
//Check if values already exist
for (TableItem item : fMainTable.getItems()) {
if (item.getText(0).equals(tableStrs[0])) {
newItem = item;
}
}
if (null == newItem) {
newItem = new TableItem(fMainTable, SWT.NONE);
}
fMainTable.showItem(newItem);
newItem.setText(tableStrs);
}
if (null != newItem) {
fMainTable.showItem(newItem);
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
R4EUIDialogFactory.getInstance().removeParticipantInputDialog();
return;
}
final TableItem newItem = new TableItem(fMainTable, SWT.NONE);
fMainTable.showItem(newItem);
if (aEditableWidgetClass.equals(Text.class)) {
fEditableControl = new Text(fMainTable, SWT.SINGLE | SWT.BORDER);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((Text) fEditableControl).getText());
}
});
((Text) fEditableControl).addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent ke) {
if (ke.keyCode == SWT.CR) {
return;
}
}
public void keyPressed(KeyEvent ke) {
// Nothing to do
}
});
} else if (aEditableWidgetClass.equals(CCombo.class)) {
fEditableControl = new CCombo(fMainTable, SWT.BORDER | SWT.READ_ONLY);
//Only add the values not already in the table in the CCombo box
final List<String> currentValues = new ArrayList<String>();
for (String currentValue : fValues) {
currentValues.add(currentValue);
}
final TableItem[] currentItems = fMainTable.getItems();
for (TableItem currentItem : currentItems) {
if (currentValues.contains(currentItem.getText())) {
currentValues.remove(currentItem.getText());
}
}
((CCombo) fEditableControl).setItems(currentValues.toArray(new String[currentValues.size()]));
((CCombo) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((CCombo) fEditableControl).getText());
}
});
} else if (aEditableWidgetClass.equals(Date.class)) {
fEditableControl = new Text(fMainTable, SWT.NONE);
final DateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.DEFAULT_DATE_FORMAT);
final String[] data = { ((Text) fEditableControl).getText(),
dateFormat.format(Calendar.getInstance().getTime()) };
newItem.setText(data);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
//Only accept numbers
String newText = ((Text) fEditableControl).getText();
try {
Integer.valueOf(newText);
} catch (NumberFormatException nfe) {
if (newText.length() > 0) {
newText = newText.substring(0, newText.length() - 1);
((Text) fEditableControl).setText(newText);
((Text) fEditableControl).setSelection(newText.length());
}
}
newItem.setText(0, newText);
}
});
} else {
return;
}
fEditableControl.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
((Control) fe.getSource()).dispose();
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
+ final int numColumns = fMainTable.getColumnCount();
+ boolean isSameItem = false;
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
return;
}
}
//If items are already present, do not consider the duplicates
if (items.length > 1) {
for (int i = 0; i < items.length; i++) {
for (int j = i + 1; j < items.length; j++) {
- if (items[i].getText().equals(items[j].getText())) {
+ isSameItem = true;
+ for (int k = 0; k < numColumns; k++) {
+ if (!items[i].getText(k).equals(items[j].getText(k))) {
+ isSameItem = false;
+ break; //at least one column is different go to next item
+ }
+ }
+ if (isSameItem) {
fMainTable.remove(j);
return;
}
}
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent fe) {
//Nothing to do
}
});
fEditableControl.setFocus();
final TableEditor editor = new TableEditor(fMainTable);
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(fEditableControl, newItem, 0);
fRemoveButton.setEnabled(true);
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
fRemoveButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fRemoveButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final int numItems = fMainTable.getItemCount();
if (numItems > 0) {
//Find the table index for the first control
final Control[] controls = fMainTable.getChildren();
final int firstControlIndex = numItems - controls.length;
//Currently selected item
int tableItemIndex = fMainTable.getSelectionIndex();
if (R4EUIConstants.INVALID_VALUE == tableItemIndex) {
//Remove the selected element (and control if there is one) or the last one if none is selected
tableItemIndex = numItems - 1;
}
if (tableItemIndex >= firstControlIndex) {
controls[tableItemIndex - firstControlIndex].dispose();
}
fMainTable.getItem(tableItemIndex).dispose();
}
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
if (null != fListener) {
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
fMainTable.redraw();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
}
/**
* Method removeAll.
*/
public void removeAll() {
fMainTable.removeAll();
}
/**
* Method addItem.
*
* @return Item
*/
public Item addItem() {
return new TableItem(fMainTable, SWT.NONE);
}
/**
* Method getItem.
*
* @param aIndex
* - int
* @return Item
*/
public Item getItem(int aIndex) {
return fMainTable.getItem(aIndex);
}
/**
* Method getSelectedItem.
*
* @return Item
*/
public Item getSelectedItem() {
if (fMainTable.getSelection().length == 0) {
return null;
}
return fMainTable.getSelection()[0]; //Only one element selectable at any given time
}
/**
* Method getItems.
*
* @return Item[]
*/
public Item[] getItems() {
return fMainTable.getItems();
}
/**
* Method getItemCount.
*
* @return int
*/
public int getItemCount() {
return fMainTable.getItemCount();
}
/**
* Method setEnabled.
*
* @param aEnabled
* - boolean
*/
public void setEnabled(boolean aEnabled) {
fMainComposite.setEnabled(aEnabled);
fMainTable.setEnabled(aEnabled);
if (!aEnabled) {
fAddButton.setEnabled(aEnabled);
fRemoveButton.setEnabled(aEnabled);
} else {
updateButtons();
}
}
/**
* Method setVisible.
*
* @param aVisible
* - boolean
*/
public void setVisible(boolean aVisible) {
fMainComposite.setVisible(aVisible);
fMainTable.setVisible(aVisible);
fAddButton.setVisible(aVisible);
fRemoveButton.setVisible(aVisible);
}
/**
* Method getComposite.
*
* @return Composite
*/
public Composite getComposite() {
return fMainComposite;
}
/**
* Method setEditableValues.
*
* @param aValues
* - String[]
*/
public void setEditableValues(String[] aValues) {
fValues = aValues;
if (null == fValues || 0 == fValues.length) {
fAddButton.setEnabled(false);
} else {
fAddButton.setEnabled(true);
}
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
}
/**
* Method setTableHeader.
*
* @param aIndex
* int
* @param aText
* String
*/
public void setTableHeader(int aIndex, String aText) {
try {
final TableColumn column = fMainTable.getColumn(aIndex);
column.setText(aText);
updateTable();
} catch (IllegalArgumentException e) {
R4EUIPlugin.Ftracer.traceWarning("Exception: " + e.toString() + " (" + e.getMessage() + ")");
R4EUIPlugin.getDefault().logWarning("Exception: " + e.toString(), e);
}
}
/**
* Method setToolTipText.
*
* @param aTooltip
* String
*/
public void setToolTipText(String aTooltip) {
fMainComposite.setToolTipText(aTooltip);
}
/**
* Method updateButtons.
*/
public void updateButtons() {
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
fAddButton.setEnabled(true);
}
/**
* Method updateButtons.
*/
public void updateTable() {
for (TableColumn column : fMainTable.getColumns()) {
column.pack();
}
}
//Test methods
/**
* Method remove.
*
* @param removeStr
*/
public void remove(String removeStr) {
for (TableItem item : fMainTable.getItems()) {
if (item.getText().equals(removeStr)) {
fMainTable.setSelection(item);
}
}
fRemoveButton.notifyListeners(SWT.Selection, null);
}
/**
* Method add.
*
* @param addStr
*/
public void add(String addStr) {
fAddButton.notifyListeners(SWT.Selection, null);
if (null != fEditableControl) {
if (fEditableControl instanceof Text) {
((Text) fEditableControl).setText(addStr);
} else if (fEditableControl instanceof CCombo) {
String[] items = ((CCombo) fEditableControl).getItems();
for (int index = 0; index < items.length; index++) {
if (items[index].equals(addStr)) {
((CCombo) fEditableControl).select(index);
}
}
}
}
}
}
| false | true | public void createEditableListFromTable(FormToolkit aToolkit, final Class<?> aEditableWidgetClass) {
final Composite tableComposite = (null != aToolkit) ? aToolkit.createComposite(fMainComposite) : new Composite(
fMainComposite, SWT.NONE);
fMainTable = (null != aToolkit)
? aToolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.BORDER)
: new Table(tableComposite, SWT.FULL_SELECTION | SWT.BORDER);
final GridData tableCompositeData = new GridData(GridData.FILL, GridData.FILL, true, true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
tableCompositeData.horizontalSpan = 1;
} else {
tableCompositeData.horizontalSpan = 2;
}
final TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
final TableColumn tableColumn = new TableColumn(fMainTable, SWT.NONE, 0);
final TableColumn tableColumn2;
fMainTable.setLinesVisible(true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
fMainTable.setHeaderVisible(true);
tableColumn2 = new TableColumn(fMainTable, SWT.NONE, 1);
if (aEditableWidgetClass.equals(Date.class)) {
tableColumn.setText(R4EUIConstants.SPENT_TIME_COLUMN_HEADER);
tableColumn2.setText(R4EUIConstants.ENTRY_TIME_COLUMN_HEADER);
} else if (aEditableWidgetClass.equals(Label.class)) {
tableColumn.setText(R4EUIConstants.ID_LABEL);
tableColumn2.setText(R4EUIConstants.EMAIL_LABEL);
}
tableColumn.pack();
tableColumn2.pack();
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(50, tableColumn.getWidth() * 2, true));
tableColumnLayout.setColumnData(tableColumn2, new ColumnWeightData(50, tableColumn.getWidth(), true));
} else {
tableColumn2 = null; //only 1 column
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(10, 100, true));
}
tableComposite.setLayoutData(tableCompositeData);
fMainComposite.addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
//TODO: This does not work 100% as resizing the colums lags when the parent area gets shrinked quickly.
// This causes the rightmost part of the table composite to be clipped away.
// This will need to be improved, see bug 356857.
final Rectangle area = fMainTable.getClientArea();
final Point size = tableComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
final ScrollBar vBar = fMainTable.getVerticalBar();
final int vBarWidth = vBar.getSize().x;
int width = area.width - vBarWidth * 3;
if (width < 0) {
return;
}
if (size.y > area.height + fMainTable.getHeaderHeight()) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
width -= vBarWidth;
}
// Set column width first and then resize the table to
// match the client area width
if (null != tableColumn2) {
tableColumn.setWidth(width / 2);
tableColumn2.setWidth(width - tableColumn.getWidth());
} else {
tableColumn.setWidth(width);
}
}
public void controlMoved(ControlEvent e) {
// ignor
}
});
fMainTable.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent e) {
//Do nothing
}
});
fMainTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
fListener.itemSelected(fMainTable.getSelection()[0], fInstanceId); //Only 1 element selected at any given time
}
});
final Composite buttonsComposite = (null != aToolkit)
? aToolkit.createComposite(fMainComposite)
: new Composite(fMainComposite, SWT.NONE);
buttonsComposite.setLayout(new GridLayout());
buttonsComposite.setLayoutData(new GridData(GridData.CENTER, SWT.TOP, false, false));
fAddButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite, R4EUIConstants.BUTTON_ADD_LABEL,
SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fAddButton.setText(R4EUIConstants.BUTTON_ADD_LABEL);
if (aEditableWidgetClass.equals(CCombo.class)) {
if (null == fValues || 0 == fValues.length) {
fAddButton.setEnabled(false);
}
}
fRemoveButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite,
R4EUIConstants.BUTTON_REMOVE_LABEL, SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fRemoveButton.setText(R4EUIConstants.BUTTON_REMOVE_LABEL);
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
fAddButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fAddButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (aEditableWidgetClass.equals(Label.class)) {
final IParticipantInputDialog dialog = R4EUIDialogFactory.getInstance().getParticipantInputDialog(
false);
final int result = dialog.open();
if (result == Window.OK) {
TableItem newItem = null;
for (R4EParticipant participant : dialog.getParticipants()) {
newItem = null;
String[] tableStrs = new String[2];
tableStrs[0] = participant.getId();
tableStrs[1] = participant.getEmail();
//Check if values already exist
for (TableItem item : fMainTable.getItems()) {
if (item.getText(0).equals(tableStrs[0])) {
newItem = item;
}
}
if (null == newItem) {
newItem = new TableItem(fMainTable, SWT.NONE);
}
fMainTable.showItem(newItem);
newItem.setText(tableStrs);
}
if (null != newItem) {
fMainTable.showItem(newItem);
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
R4EUIDialogFactory.getInstance().removeParticipantInputDialog();
return;
}
final TableItem newItem = new TableItem(fMainTable, SWT.NONE);
fMainTable.showItem(newItem);
if (aEditableWidgetClass.equals(Text.class)) {
fEditableControl = new Text(fMainTable, SWT.SINGLE | SWT.BORDER);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((Text) fEditableControl).getText());
}
});
((Text) fEditableControl).addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent ke) {
if (ke.keyCode == SWT.CR) {
return;
}
}
public void keyPressed(KeyEvent ke) {
// Nothing to do
}
});
} else if (aEditableWidgetClass.equals(CCombo.class)) {
fEditableControl = new CCombo(fMainTable, SWT.BORDER | SWT.READ_ONLY);
//Only add the values not already in the table in the CCombo box
final List<String> currentValues = new ArrayList<String>();
for (String currentValue : fValues) {
currentValues.add(currentValue);
}
final TableItem[] currentItems = fMainTable.getItems();
for (TableItem currentItem : currentItems) {
if (currentValues.contains(currentItem.getText())) {
currentValues.remove(currentItem.getText());
}
}
((CCombo) fEditableControl).setItems(currentValues.toArray(new String[currentValues.size()]));
((CCombo) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((CCombo) fEditableControl).getText());
}
});
} else if (aEditableWidgetClass.equals(Date.class)) {
fEditableControl = new Text(fMainTable, SWT.NONE);
final DateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.DEFAULT_DATE_FORMAT);
final String[] data = { ((Text) fEditableControl).getText(),
dateFormat.format(Calendar.getInstance().getTime()) };
newItem.setText(data);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
//Only accept numbers
String newText = ((Text) fEditableControl).getText();
try {
Integer.valueOf(newText);
} catch (NumberFormatException nfe) {
if (newText.length() > 0) {
newText = newText.substring(0, newText.length() - 1);
((Text) fEditableControl).setText(newText);
((Text) fEditableControl).setSelection(newText.length());
}
}
newItem.setText(0, newText);
}
});
} else {
return;
}
fEditableControl.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
((Control) fe.getSource()).dispose();
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
return;
}
}
//If items are already present, do not consider the duplicates
if (items.length > 1) {
for (int i = 0; i < items.length; i++) {
for (int j = i + 1; j < items.length; j++) {
if (items[i].getText().equals(items[j].getText())) {
fMainTable.remove(j);
return;
}
}
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent fe) {
//Nothing to do
}
});
fEditableControl.setFocus();
final TableEditor editor = new TableEditor(fMainTable);
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(fEditableControl, newItem, 0);
fRemoveButton.setEnabled(true);
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
fRemoveButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fRemoveButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final int numItems = fMainTable.getItemCount();
if (numItems > 0) {
//Find the table index for the first control
final Control[] controls = fMainTable.getChildren();
final int firstControlIndex = numItems - controls.length;
//Currently selected item
int tableItemIndex = fMainTable.getSelectionIndex();
if (R4EUIConstants.INVALID_VALUE == tableItemIndex) {
//Remove the selected element (and control if there is one) or the last one if none is selected
tableItemIndex = numItems - 1;
}
if (tableItemIndex >= firstControlIndex) {
controls[tableItemIndex - firstControlIndex].dispose();
}
fMainTable.getItem(tableItemIndex).dispose();
}
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
if (null != fListener) {
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
fMainTable.redraw();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
}
| public void createEditableListFromTable(FormToolkit aToolkit, final Class<?> aEditableWidgetClass) {
final Composite tableComposite = (null != aToolkit) ? aToolkit.createComposite(fMainComposite) : new Composite(
fMainComposite, SWT.NONE);
fMainTable = (null != aToolkit)
? aToolkit.createTable(tableComposite, SWT.FULL_SELECTION | SWT.BORDER)
: new Table(tableComposite, SWT.FULL_SELECTION | SWT.BORDER);
final GridData tableCompositeData = new GridData(GridData.FILL, GridData.FILL, true, true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
tableCompositeData.horizontalSpan = 1;
} else {
tableCompositeData.horizontalSpan = 2;
}
final TableColumnLayout tableColumnLayout = new TableColumnLayout();
tableComposite.setLayout(tableColumnLayout);
final TableColumn tableColumn = new TableColumn(fMainTable, SWT.NONE, 0);
final TableColumn tableColumn2;
fMainTable.setLinesVisible(true);
if (aEditableWidgetClass.equals(Date.class) || aEditableWidgetClass.equals(Label.class)) {
fMainTable.setHeaderVisible(true);
tableColumn2 = new TableColumn(fMainTable, SWT.NONE, 1);
if (aEditableWidgetClass.equals(Date.class)) {
tableColumn.setText(R4EUIConstants.SPENT_TIME_COLUMN_HEADER);
tableColumn2.setText(R4EUIConstants.ENTRY_TIME_COLUMN_HEADER);
} else if (aEditableWidgetClass.equals(Label.class)) {
tableColumn.setText(R4EUIConstants.ID_LABEL);
tableColumn2.setText(R4EUIConstants.EMAIL_LABEL);
}
tableColumn.pack();
tableColumn2.pack();
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(50, tableColumn.getWidth() * 2, true));
tableColumnLayout.setColumnData(tableColumn2, new ColumnWeightData(50, tableColumn.getWidth(), true));
} else {
tableColumn2 = null; //only 1 column
tableColumnLayout.setColumnData(tableColumn, new ColumnWeightData(10, 100, true));
}
tableComposite.setLayoutData(tableCompositeData);
fMainComposite.addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
//TODO: This does not work 100% as resizing the colums lags when the parent area gets shrinked quickly.
// This causes the rightmost part of the table composite to be clipped away.
// This will need to be improved, see bug 356857.
final Rectangle area = fMainTable.getClientArea();
final Point size = tableComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
final ScrollBar vBar = fMainTable.getVerticalBar();
final int vBarWidth = vBar.getSize().x;
int width = area.width - vBarWidth * 3;
if (width < 0) {
return;
}
if (size.y > area.height + fMainTable.getHeaderHeight()) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
width -= vBarWidth;
}
// Set column width first and then resize the table to
// match the client area width
if (null != tableColumn2) {
tableColumn.setWidth(width / 2);
tableColumn2.setWidth(width - tableColumn.getWidth());
} else {
tableColumn.setWidth(width);
}
}
public void controlMoved(ControlEvent e) {
// ignor
}
});
fMainTable.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent e) {
//Do nothing
}
});
fMainTable.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
fListener.itemSelected(fMainTable.getSelection()[0], fInstanceId); //Only 1 element selected at any given time
}
});
final Composite buttonsComposite = (null != aToolkit)
? aToolkit.createComposite(fMainComposite)
: new Composite(fMainComposite, SWT.NONE);
buttonsComposite.setLayout(new GridLayout());
buttonsComposite.setLayoutData(new GridData(GridData.CENTER, SWT.TOP, false, false));
fAddButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite, R4EUIConstants.BUTTON_ADD_LABEL,
SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fAddButton.setText(R4EUIConstants.BUTTON_ADD_LABEL);
if (aEditableWidgetClass.equals(CCombo.class)) {
if (null == fValues || 0 == fValues.length) {
fAddButton.setEnabled(false);
}
}
fRemoveButton = (null != aToolkit) ? aToolkit.createButton(buttonsComposite,
R4EUIConstants.BUTTON_REMOVE_LABEL, SWT.NONE) : new Button(buttonsComposite, SWT.NONE);
fRemoveButton.setText(R4EUIConstants.BUTTON_REMOVE_LABEL);
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
fAddButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fAddButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (aEditableWidgetClass.equals(Label.class)) {
final IParticipantInputDialog dialog = R4EUIDialogFactory.getInstance().getParticipantInputDialog(
false);
final int result = dialog.open();
if (result == Window.OK) {
TableItem newItem = null;
for (R4EParticipant participant : dialog.getParticipants()) {
newItem = null;
String[] tableStrs = new String[2];
tableStrs[0] = participant.getId();
tableStrs[1] = participant.getEmail();
//Check if values already exist
for (TableItem item : fMainTable.getItems()) {
if (item.getText(0).equals(tableStrs[0])) {
newItem = item;
}
}
if (null == newItem) {
newItem = new TableItem(fMainTable, SWT.NONE);
}
fMainTable.showItem(newItem);
newItem.setText(tableStrs);
}
if (null != newItem) {
fMainTable.showItem(newItem);
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
R4EUIDialogFactory.getInstance().removeParticipantInputDialog();
return;
}
final TableItem newItem = new TableItem(fMainTable, SWT.NONE);
fMainTable.showItem(newItem);
if (aEditableWidgetClass.equals(Text.class)) {
fEditableControl = new Text(fMainTable, SWT.SINGLE | SWT.BORDER);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((Text) fEditableControl).getText());
}
});
((Text) fEditableControl).addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent ke) {
if (ke.keyCode == SWT.CR) {
return;
}
}
public void keyPressed(KeyEvent ke) {
// Nothing to do
}
});
} else if (aEditableWidgetClass.equals(CCombo.class)) {
fEditableControl = new CCombo(fMainTable, SWT.BORDER | SWT.READ_ONLY);
//Only add the values not already in the table in the CCombo box
final List<String> currentValues = new ArrayList<String>();
for (String currentValue : fValues) {
currentValues.add(currentValue);
}
final TableItem[] currentItems = fMainTable.getItems();
for (TableItem currentItem : currentItems) {
if (currentValues.contains(currentItem.getText())) {
currentValues.remove(currentItem.getText());
}
}
((CCombo) fEditableControl).setItems(currentValues.toArray(new String[currentValues.size()]));
((CCombo) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
newItem.setText(((CCombo) fEditableControl).getText());
}
});
} else if (aEditableWidgetClass.equals(Date.class)) {
fEditableControl = new Text(fMainTable, SWT.NONE);
final DateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.DEFAULT_DATE_FORMAT);
final String[] data = { ((Text) fEditableControl).getText(),
dateFormat.format(Calendar.getInstance().getTime()) };
newItem.setText(data);
((Text) fEditableControl).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
//Only accept numbers
String newText = ((Text) fEditableControl).getText();
try {
Integer.valueOf(newText);
} catch (NumberFormatException nfe) {
if (newText.length() > 0) {
newText = newText.substring(0, newText.length() - 1);
((Text) fEditableControl).setText(newText);
((Text) fEditableControl).setSelection(newText.length());
}
}
newItem.setText(0, newText);
}
});
} else {
return;
}
fEditableControl.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
((Control) fe.getSource()).dispose();
//Send items updated notification
if (null != fListener) {
//If items are empty, do not consider them
final TableItem[] items = fMainTable.getItems();
final int numColumns = fMainTable.getColumnCount();
boolean isSameItem = false;
for (int i = 0; i < items.length; i++) {
if (items[i].getText().trim().length() < 1) {
fMainTable.remove(i);
return;
}
}
//If items are already present, do not consider the duplicates
if (items.length > 1) {
for (int i = 0; i < items.length; i++) {
for (int j = i + 1; j < items.length; j++) {
isSameItem = true;
for (int k = 0; k < numColumns; k++) {
if (!items[i].getText(k).equals(items[j].getText(k))) {
isSameItem = false;
break; //at least one column is different go to next item
}
}
if (isSameItem) {
fMainTable.remove(j);
return;
}
}
}
}
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
}
public void focusGained(FocusEvent fe) {
//Nothing to do
}
});
fEditableControl.setFocus();
final TableEditor editor = new TableEditor(fMainTable);
editor.grabHorizontal = true;
editor.grabVertical = true;
editor.setEditor(fEditableControl, newItem, 0);
fRemoveButton.setEnabled(true);
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
fRemoveButton.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, false));
fRemoveButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
final int numItems = fMainTable.getItemCount();
if (numItems > 0) {
//Find the table index for the first control
final Control[] controls = fMainTable.getChildren();
final int firstControlIndex = numItems - controls.length;
//Currently selected item
int tableItemIndex = fMainTable.getSelectionIndex();
if (R4EUIConstants.INVALID_VALUE == tableItemIndex) {
//Remove the selected element (and control if there is one) or the last one if none is selected
tableItemIndex = numItems - 1;
}
if (tableItemIndex >= firstControlIndex) {
controls[tableItemIndex - firstControlIndex].dispose();
}
fMainTable.getItem(tableItemIndex).dispose();
}
if (0 == fMainTable.getItemCount()) {
fRemoveButton.setEnabled(false);
} else {
fRemoveButton.setEnabled(true);
}
if (null != fListener) {
fListener.itemsUpdated(fMainTable.getItems(), fInstanceId);
}
fMainTable.redraw();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
}
});
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.