diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/org/opensolaris/opengrok/index/IndexDatabase.java b/src/org/opensolaris/opengrok/index/IndexDatabase.java
index aed9c2c2..43966b3e 100644
--- a/src/org/opensolaris/opengrok/index/IndexDatabase.java
+++ b/src/org/opensolaris/opengrok/index/IndexDatabase.java
@@ -1,1198 +1,1197 @@
/*
* CDDL HEADER START
*
* 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.
*
* See LICENSE.txt included in this distribution 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 LICENSE.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]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
*/
package org.opensolaris.opengrok.index;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.*;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.NoLockFactory;
import org.apache.lucene.store.SimpleFSLockFactory;
import org.apache.lucene.util.BytesRef;
import org.opensolaris.opengrok.analysis.AnalyzerGuru;
import org.opensolaris.opengrok.analysis.Ctags;
import org.opensolaris.opengrok.analysis.Definitions;
import org.opensolaris.opengrok.analysis.FileAnalyzer;
import org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.configuration.RuntimeEnvironment;
import org.opensolaris.opengrok.history.HistoryException;
import org.opensolaris.opengrok.history.HistoryGuru;
import org.opensolaris.opengrok.search.QueryBuilder;
import org.opensolaris.opengrok.search.SearchEngine;
import org.opensolaris.opengrok.util.IOUtils;
import org.opensolaris.opengrok.web.Util;
/**
* This class is used to create / update the index databases. Currently we use
* one index database per project.
*
* @author Trond Norbye
* @author Lubos Kosco , update for lucene 4.2.0
*/
public class IndexDatabase {
private Project project;
private FSDirectory indexDirectory;
private IndexWriter writer;
private TermsEnum uidIter;
private IgnoredNames ignoredNames;
private Filter includedNames;
private AnalyzerGuru analyzerGuru;
private File xrefDir;
private boolean interrupted;
private List<IndexChangedListener> listeners;
private File dirtyFile;
private final Object lock = new Object();
private boolean dirty;
private boolean running;
private List<String> directories;
static final Logger log = Logger.getLogger(IndexDatabase.class.getName());
private Ctags ctags;
private LockFactory lockfact;
private final BytesRef emptyBR = new BytesRef("");
//Directory where we store indexes
private static final String INDEX_DIR="index";
/**
* Create a new instance of the Index Database. Use this constructor if you
* don't use any projects
*
* @throws java.io.IOException if an error occurs while creating directories
*/
public IndexDatabase() throws IOException {
this(null);
}
/**
* Create a new instance of an Index Database for a given project
*
* @param project the project to create the database for
* @throws java.io.IOException if an errror occurs while creating
* directories
*/
public IndexDatabase(Project project) throws IOException {
this.project = project;
lockfact = new SimpleFSLockFactory();
initialize();
}
/**
* Update the index database for all of the projects. Print progress to
* standard out.
*
* @param executor An executor to run the job
* @throws IOException if an error occurs
*/
public static void updateAll(ExecutorService executor) throws IOException {
updateAll(executor, null);
}
/**
* Update the index database for all of the projects
*
* @param executor An executor to run the job
* @param listener where to signal the changes to the database
* @throws IOException if an error occurs
*/
static void updateAll(ExecutorService executor, IndexChangedListener listener) throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
List<IndexDatabase> dbs = new ArrayList<>();
if (env.hasProjects()) {
for (Project project : env.getProjects()) {
dbs.add(new IndexDatabase(project));
}
} else {
dbs.add(new IndexDatabase());
}
for (IndexDatabase d : dbs) {
final IndexDatabase db = d;
if (listener != null) {
db.addIndexChangedListener(listener);
}
executor.submit(new Runnable() {
@Override
public void run() {
try {
db.update();
} catch (Throwable e) {
log.log(Level.SEVERE, "Problem updating lucene index database: ", e);
}
}
});
}
}
/**
* Update the index database for a number of sub-directories
*
* @param executor An executor to run the job
* @param listener where to signal the changes to the database
* @param paths
* @throws IOException if an error occurs
*/
public static void update(ExecutorService executor, IndexChangedListener listener, List<String> paths) throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
List<IndexDatabase> dbs = new ArrayList<>();
for (String path : paths) {
Project project = Project.getProject(path);
if (project == null && env.hasProjects()) {
log.log(Level.WARNING, "Could not find a project for \"{0}\"", path);
} else {
IndexDatabase db;
try {
if (project == null) {
db = new IndexDatabase();
} else {
db = new IndexDatabase(project);
}
int idx = dbs.indexOf(db);
if (idx != -1) {
db = dbs.get(idx);
}
if (db.addDirectory(path)) {
if (idx == -1) {
dbs.add(db);
}
} else {
log.log(Level.WARNING, "Directory does not exist \"{0}\"", path);
}
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while updating index", e);
}
}
for (final IndexDatabase db : dbs) {
db.addIndexChangedListener(listener);
executor.submit(new Runnable() {
@Override
public void run() {
try {
db.update();
} catch (Throwable e) {
log.log(Level.SEVERE, "An error occured while updating index", e);
}
}
});
}
}
}
@SuppressWarnings("PMD.CollapsibleIfStatements")
private void initialize() throws IOException {
synchronized (this) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File indexDir = new File(env.getDataRootFile(), INDEX_DIR);
if (project != null) {
indexDir = new File(indexDir, project.getPath());
}
if (!indexDir.exists() && !indexDir.mkdirs()) {
// to avoid race conditions, just recheck..
if (!indexDir.exists()) {
throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]");
}
}
if (!env.isUsingLuceneLocking()) {
lockfact = NoLockFactory.getNoLockFactory();
}
indexDirectory = FSDirectory.open(indexDir, lockfact);
ignoredNames = env.getIgnoredNames();
includedNames = env.getIncludedNames();
analyzerGuru = new AnalyzerGuru();
if (env.isGenerateHtml()) {
xrefDir = new File(env.getDataRootFile(), "xref");
}
listeners = new ArrayList<>();
dirtyFile = new File(indexDir, "dirty");
dirty = dirtyFile.exists();
directories = new ArrayList<>();
}
}
/**
* By default the indexer will traverse all directories in the project. If
* you add directories with this function update will just process the
* specified directories.
*
* @param dir The directory to scan
* @return <code>true</code> if the file is added, false otherwise
*/
@SuppressWarnings("PMD.UseStringBufferForStringAppends")
public boolean addDirectory(String dir) {
String directory = dir;
if (directory.startsWith("\\")) {
directory = directory.replace('\\', '/');
} else if (directory.charAt(0) != '/') {
directory = "/" + directory;
}
File file = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), directory);
if (file.exists()) {
directories.add(directory);
return true;
}
return false;
}
/**
* Update the content of this index database
*
* @throws IOException if an error occurs
* @throws HistoryException if an error occurs when accessing the history
*/
public void update() throws IOException, HistoryException {
synchronized (lock) {
if (running) {
throw new IOException("Indexer already running!");
}
running = true;
interrupted = false;
}
String ctgs = RuntimeEnvironment.getInstance().getCtags();
if (ctgs != null) {
ctags = new Ctags();
ctags.setBinary(ctgs);
}
if (ctags == null) {
log.severe("Unable to run ctags! searching definitions will not work!");
}
if (ctags != null) {
String filename = RuntimeEnvironment.getInstance().getCTagsExtraOptionsFile();
if (filename != null) {
ctags.setCTagsExtraOptionsFile(filename);
}
}
try {
Analyzer analyzer = AnalyzerGuru.getAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(SearchEngine.LUCENE_VERSION, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwc.setRAMBufferSizeMB(RuntimeEnvironment.getInstance().getRamBufferSize());
writer = new IndexWriter(indexDirectory, iwc);
writer.commit(); // to make sure index exists on the disk
if (directories.isEmpty()) {
if (project == null) {
directories.add("");
} else {
directories.add(project.getPath());
}
}
for (String dir : directories) {
File sourceRoot;
if ("".equals(dir)) {
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
} else {
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
}
HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
String startuid = Util.path2uid(dir, "");
IndexReader reader = DirectoryReader.open(indexDirectory); // open existing index
Terms terms = null;
int numDocs = reader.numDocs();
if (numDocs > 0) {
Fields uFields = MultiFields.getFields(reader);//reader.getTermVectors(0);
terms = uFields.terms(QueryBuilder.U);
}
try {
if (numDocs > 0) {
uidIter = terms.iterator(uidIter);
TermsEnum.SeekStatus stat = uidIter.seekCeil(new BytesRef(startuid)); //init uid
if (stat==TermsEnum.SeekStatus.END) {
uidIter=null;
log.log(Level.WARNING,
"Couldn't find a start term for {0}, empty u field?",
startuid);
}
}
// The code below traverses the tree to get total count.
int file_cnt = 0;
if (RuntimeEnvironment.getInstance().isPrintProgress()) {
log.log(Level.INFO, "Counting files in {0} ...", dir);
file_cnt = indexDown(sourceRoot, dir, true, 0, 0);
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO,
"Need to process: {0} files for {1}",
new Object[]{file_cnt, dir});
}
}
indexDown(sourceRoot, dir, false, 0, file_cnt);
while (uidIter != null && uidIter.term() != null
&& uidIter.term().utf8ToString().startsWith(startuid)) {
removeFile();
BytesRef next = uidIter.next();
if (next==null) {
uidIter=null;
}
}
} finally {
reader.close();
}
}
} finally {
if (writer != null) {
try {
writer.prepareCommit();
writer.commit();
writer.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing writer", e);
}
}
if (ctags != null) {
try {
ctags.close();
} catch (IOException e) {
log.log(Level.WARNING,
"An error occured while closing ctags process", e);
}
}
synchronized (lock) {
running = false;
}
}
if (!isInterrupted() && isDirty()) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File timestamp = new File(env.getDataRootFile(), "timestamp");
+ String purpose = "used for timestamping the index database.";
if (timestamp.exists()) {
if (!timestamp.setLastModified(System.currentTimeMillis())) {
- log.log(Level.WARNING, "Failed to set last modified time on ''{0}'', "
- + "used for timestamping the index database.",
- timestamp.getAbsolutePath());
+ log.log(Level.WARNING, "Failed to set last modified time on ''{0}'', {1}",
+ new Object[]{timestamp.getAbsolutePath(), purpose});
}
} else {
if (!timestamp.createNewFile()) {
- log.log(Level.WARNING, "Failed to create file ''{0}'', "
- + "used for timestamping the index database.",
- timestamp.getAbsolutePath());
+ log.log(Level.WARNING, "Failed to create file ''{0}'', {1}",
+ new Object[]{timestamp.getAbsolutePath(), purpose});
}
}
}
}
/**
* Optimize all index databases
*
* @param executor An executor to run the job
* @throws IOException if an error occurs
*/
static void optimizeAll(ExecutorService executor) throws IOException {
List<IndexDatabase> dbs = new ArrayList<>();
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.hasProjects()) {
for (Project project : env.getProjects()) {
dbs.add(new IndexDatabase(project));
}
} else {
dbs.add(new IndexDatabase());
}
for (IndexDatabase d : dbs) {
final IndexDatabase db = d;
if (db.isDirty()) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
db.update();
} catch (Throwable e) {
log.log(Level.SEVERE,
"Problem updating lucene index database: ", e);
}
}
});
}
}
}
/**
* Optimize the index database
*/
public void optimize() {
synchronized (lock) {
if (running) {
log.warning("Optimize terminated... Someone else is updating / optimizing it!");
return;
}
running = true;
}
IndexWriter wrt = null;
try {
log.info("Optimizing the index ... ");
Analyzer analyzer = new StandardAnalyzer(SearchEngine.LUCENE_VERSION);
IndexWriterConfig conf = new IndexWriterConfig(SearchEngine.LUCENE_VERSION, analyzer);
conf.setOpenMode(OpenMode.CREATE_OR_APPEND);
wrt = new IndexWriter(indexDirectory, conf);
wrt.forceMerge(1); // this is deprecated and not needed anymore
log.info("done");
synchronized (lock) {
if (dirtyFile.exists() && !dirtyFile.delete()) {
log.log(Level.FINE, "Failed to remove \"dirty-file\": {0}",
dirtyFile.getAbsolutePath());
}
dirty = false;
}
} catch (IOException e) {
log.log(Level.SEVERE, "ERROR: optimizing index: {0}", e);
} finally {
if (wrt != null) {
try {
wrt.close();
} catch (IOException e) {
log.log(Level.WARNING,
"An error occured while closing writer", e);
}
}
synchronized (lock) {
running = false;
}
}
}
private boolean isDirty() {
synchronized (lock) {
return dirty;
}
}
private void setDirty() {
synchronized (lock) {
try {
if (!dirty && !dirtyFile.createNewFile()) {
if (!dirtyFile.exists()) {
log.log(Level.FINE,
"Failed to create \"dirty-file\": {0}",
dirtyFile.getAbsolutePath());
}
dirty = true;
}
} catch (IOException e) {
log.log(Level.FINE, "When creating dirty file: ", e);
}
}
}
/**
* Remove a stale file (uidIter.term().text()) from the index database (and
* the xref file)
*
* @throws java.io.IOException if an error occurs
*/
private void removeFile() throws IOException {
String path = Util.uid2url(uidIter.term().utf8ToString());
for (IndexChangedListener listener : listeners) {
listener.fileRemove(path);
}
writer.deleteDocuments(new Term(QueryBuilder.U, uidIter.term()));
writer.prepareCommit();
writer.commit();
File xrefFile;
if (RuntimeEnvironment.getInstance().isCompressXref()) {
xrefFile = new File(xrefDir, path + ".gz");
} else {
xrefFile = new File(xrefDir, path);
}
File parent = xrefFile.getParentFile();
if (!xrefFile.delete() && xrefFile.exists()) {
log.log(Level.INFO, "Failed to remove obsolete xref-file: {0}", xrefFile.getAbsolutePath());
}
// Remove the parent directory if it's empty
if (parent.delete()) {
log.log(Level.FINE, "Removed empty xref dir:{0}", parent.getAbsolutePath());
}
setDirty();
for (IndexChangedListener listener : listeners) {
listener.fileRemoved(path);
}
}
/**
* Add a file to the Lucene index (and generate a xref file)
*
* @param file The file to add
* @param path The path to the file (from source root)
* @throws java.io.IOException if an error occurs
*/
private void addFile(File file, String path) throws IOException {
FileAnalyzer fa;
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
fa = AnalyzerGuru.getAnalyzer(in, path);
}
for (IndexChangedListener listener : listeners) {
listener.fileAdd(path, fa.getClass().getSimpleName());
}
fa.setCtags(ctags);
fa.setProject(Project.getProject(path));
Document doc = new Document();
try (Writer xrefOut = getXrefWriter(fa, path)) {
analyzerGuru.populateDocument(doc, file, path, fa, xrefOut);
} catch (Exception e) {
log.log(Level.INFO,
"Skipped file ''{0}'' because the analyzer didn''t "
+ "understand it.",
path);
log.log(Level.FINE,
"Exception from analyzer " + fa.getClass().getName(), e);
cleanupResources(doc);
return;
}
try {
writer.addDocument(doc, fa);
} catch (Throwable t) {
cleanupResources(doc);
throw t;
}
setDirty();
for (IndexChangedListener listener : listeners) {
listener.fileAdded(path, fa.getClass().getSimpleName());
}
}
/**
* Do a best effort to clean up all resources allocated when populating
* a Lucene document. On normal execution, these resources should be
* closed automatically by the index writer once it's done with them, but
* we may not get that far if something fails.
*
* @param doc the document whose resources to clean up
*/
private void cleanupResources(Document doc) {
for (IndexableField f : doc) {
// If the field takes input from a reader, close the reader.
IOUtils.close(f.readerValue());
// If the field takes input from a token stream, close the
// token stream.
if (f instanceof Field) {
IOUtils.close(((Field) f).tokenStreamValue());
}
}
}
/**
* Check if I should accept this file into the index database
*
* @param file the file to check
* @return true if the file should be included, false otherwise
*/
private boolean accept(File file) {
if (!includedNames.isEmpty()
&& // the filter should not affect directory names
(!(file.isDirectory() || includedNames.match(file)))) {
return false;
}
if (ignoredNames.ignore(file)) {
return false;
}
String absolutePath = file.getAbsolutePath();
if (!file.canRead()) {
log.log(Level.WARNING, "Warning: could not read {0}", absolutePath);
return false;
}
try {
String canonicalPath = file.getCanonicalPath();
if (!absolutePath.equals(canonicalPath)
&& !acceptSymlink(absolutePath, canonicalPath)) {
log.log(Level.FINE, "Skipped symlink ''{0}'' -> ''{1}''",
new Object[]{absolutePath, canonicalPath});
return false;
}
//below will only let go files and directories, anything else is considered special and is not added
if (!file.isFile() && !file.isDirectory()) {
log.log(Level.WARNING, "Warning: ignored special file {0}",
absolutePath);
return false;
}
} catch (IOException exp) {
log.log(Level.WARNING, "Warning: Failed to resolve name: {0}",
absolutePath);
log.log(Level.FINE, "Stack Trace: ", exp);
}
if (file.isDirectory()) {
// always accept directories so that their files can be examined
return true;
}
if (HistoryGuru.getInstance().hasHistory(file)) {
// versioned files should always be accepted
return true;
}
// this is an unversioned file, check if it should be indexed
return !RuntimeEnvironment.getInstance().isIndexVersionedFilesOnly();
}
boolean accept(File parent, File file) {
try {
File f1 = parent.getCanonicalFile();
File f2 = file.getCanonicalFile();
if (f1.equals(f2)) {
log.log(Level.INFO, "Skipping links to itself...: {0} {1}",
new Object[]{parent.getAbsolutePath(), file.getAbsolutePath()});
return false;
}
// Now, let's verify that it's not a link back up the chain...
File t1 = f1;
while ((t1 = t1.getParentFile()) != null) {
if (f2.equals(t1)) {
log.log(Level.INFO, "Skipping links to parent...: {0} {1}",
new Object[]{parent.getAbsolutePath(), file.getAbsolutePath()});
return false;
}
}
return accept(file);
} catch (IOException ex) {
log.log(Level.WARNING, "Warning: Failed to resolve name: {0} {1}",
new Object[]{parent.getAbsolutePath(), file.getAbsolutePath()});
}
return false;
}
/**
* Check if I should accept the path containing a symlink
*
* @param absolutePath the path with a symlink to check
* @param canonicalPath the canonical path to the file
* @return true if the file should be accepted, false otherwise
*/
private boolean acceptSymlink(String absolutePath, String canonicalPath) throws IOException {
// Always accept local symlinks
if (isLocal(canonicalPath)) {
return true;
}
for (String allowedSymlink : RuntimeEnvironment.getInstance().getAllowedSymlinks()) {
if (absolutePath.startsWith(allowedSymlink)) {
String allowedTarget = new File(allowedSymlink).getCanonicalPath();
if (canonicalPath.startsWith(allowedTarget)
&& absolutePath.substring(allowedSymlink.length()).equals(canonicalPath.substring(allowedTarget.length()))) {
return true;
}
}
}
return false;
}
/**
* Check if a file is local to the current project. If we don't have
* projects, check if the file is in the source root.
*
* @param path the path to a file
* @return true if the file is local to the current repository
*/
private boolean isLocal(String path) {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
String srcRoot = env.getSourceRootPath();
boolean local = false;
if (path.startsWith(srcRoot)) {
if (env.hasProjects()) {
String relPath = path.substring(srcRoot.length());
if (project.equals(Project.getProject(relPath))) {
// File is under the current project, so it's local.
local = true;
}
} else {
// File is under source root, and we don't have projects, so
// consider it local.
local = true;
}
}
return local;
}
/**
* Generate indexes recursively
*
* @param dir the root indexDirectory to generate indexes for
* @param path the path
* @param count_only if true will just traverse the source root and count
* files
* @param cur_count current count during the traversal of the tree
* @param est_total estimate total files to process
*
*/
private int indexDown(File dir, String parent, boolean count_only,
int cur_count, int est_total) throws IOException {
int lcur_count = cur_count;
if (isInterrupted()) {
return lcur_count;
}
if (!accept(dir)) {
return lcur_count;
}
File[] files = dir.listFiles();
if (files == null) {
log.log(Level.SEVERE, "Failed to get file listing for: {0}",
dir.getAbsolutePath());
return lcur_count;
}
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File p1, File p2) {
return p1.getName().compareTo(p2.getName());
}
});
for (File file : files) {
if (accept(dir, file)) {
String path = parent + '/' + file.getName();
if (file.isDirectory()) {
lcur_count = indexDown(file, path, count_only, lcur_count, est_total);
} else {
lcur_count++;
if (count_only) {
continue;
}
if (RuntimeEnvironment.getInstance().isPrintProgress()
&& est_total > 0 && log.isLoggable(Level.INFO)) {
log.log(Level.INFO, "Progress: {0} ({1}%)",
new Object[]{lcur_count,
(lcur_count * 100.0f / est_total)});
}
if (uidIter != null) {
String uid = Util.path2uid(path,
DateTools.timeToString(file.lastModified(),
DateTools.Resolution.MILLISECOND)); // construct uid for doc
BytesRef buid = new BytesRef(uid);
while (uidIter != null && uidIter.term() != null
&& uidIter.term().compareTo(emptyBR) !=0
&& uidIter.term().compareTo(buid) < 0) {
removeFile();
BytesRef next = uidIter.next();
if (next==null) {uidIter=null;}
}
if (uidIter != null && uidIter.term() != null
&& uidIter.term().bytesEquals(buid)) {
BytesRef next = uidIter.next(); // keep matching docs
if (next==null) {uidIter=null;}
continue;
}
}
try {
addFile(file, path);
} catch (Exception e) {
log.log(Level.WARNING,
"Failed to add file " + file.getAbsolutePath(),
e);
}
}
}
}
return lcur_count;
}
/**
* Interrupt the index generation (and the index generation will stop as
* soon as possible)
*/
public void interrupt() {
synchronized (lock) {
interrupted = true;
}
}
private boolean isInterrupted() {
synchronized (lock) {
return interrupted;
}
}
/**
* Register an object to receive events when modifications is done to the
* index database.
*
* @param listener the object to receive the events
*/
public void addIndexChangedListener(IndexChangedListener listener) {
listeners.add(listener);
}
/**
* Remove an object from the lists of objects to receive events when
* modifications is done to the index database
*
* @param listener the object to remove
*/
public void removeIndexChangedListener(IndexChangedListener listener) {
listeners.remove(listener);
}
/**
* List all files in all of the index databases
*
* @throws IOException if an error occurs
*/
public static void listAllFiles() throws IOException {
listAllFiles(null);
}
/**
* List all files in some of the index databases
*
* @param subFiles Subdirectories for the various projects to list the files
* for (or null or an empty list to dump all projects)
* @throws IOException if an error occurs
*/
public static void listAllFiles(List<String> subFiles) throws IOException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.hasProjects()) {
if (subFiles == null || subFiles.isEmpty()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
db.listFiles();
}
} else {
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null) {
log.log(Level.WARNING, "Warning: Could not find a project for \"{0}\"", path);
} else {
IndexDatabase db = new IndexDatabase(project);
db.listFiles();
}
}
}
} else {
IndexDatabase db = new IndexDatabase();
db.listFiles();
}
}
/**
* List all of the files in this index database
*
* @throws IOException If an IO error occurs while reading from the database
*/
public void listFiles() throws IOException {
IndexReader ireader = null;
TermsEnum iter=null;
Terms terms = null;
try {
ireader = DirectoryReader.open(indexDirectory); // open existing index
int numDocs = ireader.numDocs();
if (numDocs > 0) {
Fields uFields = MultiFields.getFields(ireader);//reader.getTermVectors(0);
terms = uFields.terms(QueryBuilder.U);
}
iter = terms.iterator(iter); // init uid iterator
while (iter != null && iter.term() != null) {
log.fine(Util.uid2url(iter.term().utf8ToString()));
BytesRef next=iter.next();
if (next==null) {iter=null;}
}
} finally {
if (ireader != null) {
try {
ireader.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing index reader", e);
}
}
}
}
static void listFrequentTokens() throws IOException {
listFrequentTokens(null);
}
static void listFrequentTokens(List<String> subFiles) throws IOException {
final int limit = 4;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
if (env.hasProjects()) {
if (subFiles == null || subFiles.isEmpty()) {
for (Project project : env.getProjects()) {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
} else {
for (String path : subFiles) {
Project project = Project.getProject(path);
if (project == null) {
log.log(Level.WARNING, "Warning: Could not find a project for \"{0}\"", path);
} else {
IndexDatabase db = new IndexDatabase(project);
db.listTokens(4);
}
}
}
} else {
IndexDatabase db = new IndexDatabase();
db.listTokens(limit);
}
}
public void listTokens(int freq) throws IOException {
IndexReader ireader = null;
TermsEnum iter = null;
Terms terms = null;
try {
ireader = DirectoryReader.open(indexDirectory);
int numDocs = ireader.numDocs();
if (numDocs > 0) {
Fields uFields = MultiFields.getFields(ireader);//reader.getTermVectors(0);
terms = uFields.terms(QueryBuilder.DEFS);
}
iter = terms.iterator(iter); // init uid iterator
while (iter != null && iter.term() != null) {
//if (iter.term().field().startsWith("f")) {
if (iter.docFreq() > 16 && iter.term().utf8ToString().length() > freq) {
log.warning(iter.term().utf8ToString());
}
BytesRef next = iter.next();
if (next==null) {iter=null;}
/*} else {
break;
}*/
}
} finally {
if (ireader != null) {
try {
ireader.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing index reader", e);
}
}
}
}
/**
* Get an indexReader for the Index database where a given file
*
* @param path the file to get the database for
* @return The index database where the file should be located or null if it
* cannot be located.
*/
public static IndexReader getIndexReader(String path) {
IndexReader ret = null;
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File indexDir = new File(env.getDataRootFile(), INDEX_DIR);
if (env.hasProjects()) {
Project p = Project.getProject(path);
if (p == null) {
return null;
}
indexDir = new File(indexDir, p.getPath());
}
try {
FSDirectory fdir = FSDirectory.open(indexDir, NoLockFactory.getNoLockFactory());
if (indexDir.exists() && DirectoryReader.indexExists(fdir)) {
ret = DirectoryReader.open(fdir);
}
} catch (Exception ex) {
log.log(Level.SEVERE, "Failed to open index: {0}", indexDir.getAbsolutePath());
log.log(Level.FINE, "Stack Trace: ", ex);
}
return ret;
}
/**
* Get the latest definitions for a file from the index.
*
* @param file the file whose definitions to find
* @return definitions for the file, or {@code null} if they could not be
* found
* @throws IOException if an error happens when accessing the index
* @throws ParseException if an error happens when building the Lucene query
* @throws ClassNotFoundException if the class for the stored definitions
* instance cannot be found
*/
public static Definitions getDefinitions(File file)
throws IOException, ParseException, ClassNotFoundException {
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
String path = env.getPathRelativeToSourceRoot(file, 0);
//sanitize windows path delimiters
//in order not to conflict with Lucene escape character
path=path.replace("\\", "/");
IndexReader ireader = getIndexReader(path);
if (ireader == null) {
// No index, no definitions...
return null;
}
try {
Query q = new QueryBuilder().setPath(path).build();
IndexSearcher searcher = new IndexSearcher(ireader);
TopDocs top = searcher.search(q, 1);
if (top.totalHits == 0) {
// No hits, no definitions...
return null;
}
Document doc = searcher.doc(top.scoreDocs[0].doc);
String foundPath = doc.get(QueryBuilder.PATH);
// Only use the definitions if we found an exact match.
if (path.equals(foundPath)) {
IndexableField tags = doc.getField(QueryBuilder.TAGS);
if (tags != null) {
return Definitions.deserialize(tags.binaryValue().bytes);
}
}
} finally {
ireader.close();
}
// Didn't find any definitions.
return null;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IndexDatabase other = (IndexDatabase) obj;
if (this.project != other.project && (this.project == null || !this.project.equals(other.project))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + (this.project == null ? 0 : this.project.hashCode());
return hash;
}
/**
* Get a writer to which the xref can be written, or null if no xref
* should be produced for files of this type.
*/
private Writer getXrefWriter(FileAnalyzer fa, String path) throws IOException {
Genre g = fa.getFactory().getGenre();
if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) {
File xrefFile = new File(xrefDir, path);
// If mkdirs() returns false, the failure is most likely
// because the file already exists. But to check for the
// file first and only add it if it doesn't exists would
// only increase the file IO...
if (!xrefFile.getParentFile().mkdirs()) {
assert xrefFile.getParentFile().exists();
}
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
boolean compressed = env.isCompressXref();
File file = new File(xrefDir, path + (compressed ? ".gz" : ""));
return new BufferedWriter(new OutputStreamWriter(
compressed ?
new GZIPOutputStream(new FileOutputStream(file)) :
new FileOutputStream(file)));
}
// no Xref for this analyzer
return null;
}
}
| false | true | public void update() throws IOException, HistoryException {
synchronized (lock) {
if (running) {
throw new IOException("Indexer already running!");
}
running = true;
interrupted = false;
}
String ctgs = RuntimeEnvironment.getInstance().getCtags();
if (ctgs != null) {
ctags = new Ctags();
ctags.setBinary(ctgs);
}
if (ctags == null) {
log.severe("Unable to run ctags! searching definitions will not work!");
}
if (ctags != null) {
String filename = RuntimeEnvironment.getInstance().getCTagsExtraOptionsFile();
if (filename != null) {
ctags.setCTagsExtraOptionsFile(filename);
}
}
try {
Analyzer analyzer = AnalyzerGuru.getAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(SearchEngine.LUCENE_VERSION, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwc.setRAMBufferSizeMB(RuntimeEnvironment.getInstance().getRamBufferSize());
writer = new IndexWriter(indexDirectory, iwc);
writer.commit(); // to make sure index exists on the disk
if (directories.isEmpty()) {
if (project == null) {
directories.add("");
} else {
directories.add(project.getPath());
}
}
for (String dir : directories) {
File sourceRoot;
if ("".equals(dir)) {
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
} else {
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
}
HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
String startuid = Util.path2uid(dir, "");
IndexReader reader = DirectoryReader.open(indexDirectory); // open existing index
Terms terms = null;
int numDocs = reader.numDocs();
if (numDocs > 0) {
Fields uFields = MultiFields.getFields(reader);//reader.getTermVectors(0);
terms = uFields.terms(QueryBuilder.U);
}
try {
if (numDocs > 0) {
uidIter = terms.iterator(uidIter);
TermsEnum.SeekStatus stat = uidIter.seekCeil(new BytesRef(startuid)); //init uid
if (stat==TermsEnum.SeekStatus.END) {
uidIter=null;
log.log(Level.WARNING,
"Couldn't find a start term for {0}, empty u field?",
startuid);
}
}
// The code below traverses the tree to get total count.
int file_cnt = 0;
if (RuntimeEnvironment.getInstance().isPrintProgress()) {
log.log(Level.INFO, "Counting files in {0} ...", dir);
file_cnt = indexDown(sourceRoot, dir, true, 0, 0);
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO,
"Need to process: {0} files for {1}",
new Object[]{file_cnt, dir});
}
}
indexDown(sourceRoot, dir, false, 0, file_cnt);
while (uidIter != null && uidIter.term() != null
&& uidIter.term().utf8ToString().startsWith(startuid)) {
removeFile();
BytesRef next = uidIter.next();
if (next==null) {
uidIter=null;
}
}
} finally {
reader.close();
}
}
} finally {
if (writer != null) {
try {
writer.prepareCommit();
writer.commit();
writer.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing writer", e);
}
}
if (ctags != null) {
try {
ctags.close();
} catch (IOException e) {
log.log(Level.WARNING,
"An error occured while closing ctags process", e);
}
}
synchronized (lock) {
running = false;
}
}
if (!isInterrupted() && isDirty()) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File timestamp = new File(env.getDataRootFile(), "timestamp");
if (timestamp.exists()) {
if (!timestamp.setLastModified(System.currentTimeMillis())) {
log.log(Level.WARNING, "Failed to set last modified time on ''{0}'', "
+ "used for timestamping the index database.",
timestamp.getAbsolutePath());
}
} else {
if (!timestamp.createNewFile()) {
log.log(Level.WARNING, "Failed to create file ''{0}'', "
+ "used for timestamping the index database.",
timestamp.getAbsolutePath());
}
}
}
}
| public void update() throws IOException, HistoryException {
synchronized (lock) {
if (running) {
throw new IOException("Indexer already running!");
}
running = true;
interrupted = false;
}
String ctgs = RuntimeEnvironment.getInstance().getCtags();
if (ctgs != null) {
ctags = new Ctags();
ctags.setBinary(ctgs);
}
if (ctags == null) {
log.severe("Unable to run ctags! searching definitions will not work!");
}
if (ctags != null) {
String filename = RuntimeEnvironment.getInstance().getCTagsExtraOptionsFile();
if (filename != null) {
ctags.setCTagsExtraOptionsFile(filename);
}
}
try {
Analyzer analyzer = AnalyzerGuru.getAnalyzer();
IndexWriterConfig iwc = new IndexWriterConfig(SearchEngine.LUCENE_VERSION, analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
iwc.setRAMBufferSizeMB(RuntimeEnvironment.getInstance().getRamBufferSize());
writer = new IndexWriter(indexDirectory, iwc);
writer.commit(); // to make sure index exists on the disk
if (directories.isEmpty()) {
if (project == null) {
directories.add("");
} else {
directories.add(project.getPath());
}
}
for (String dir : directories) {
File sourceRoot;
if ("".equals(dir)) {
sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile();
} else {
sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir);
}
HistoryGuru.getInstance().ensureHistoryCacheExists(sourceRoot);
String startuid = Util.path2uid(dir, "");
IndexReader reader = DirectoryReader.open(indexDirectory); // open existing index
Terms terms = null;
int numDocs = reader.numDocs();
if (numDocs > 0) {
Fields uFields = MultiFields.getFields(reader);//reader.getTermVectors(0);
terms = uFields.terms(QueryBuilder.U);
}
try {
if (numDocs > 0) {
uidIter = terms.iterator(uidIter);
TermsEnum.SeekStatus stat = uidIter.seekCeil(new BytesRef(startuid)); //init uid
if (stat==TermsEnum.SeekStatus.END) {
uidIter=null;
log.log(Level.WARNING,
"Couldn't find a start term for {0}, empty u field?",
startuid);
}
}
// The code below traverses the tree to get total count.
int file_cnt = 0;
if (RuntimeEnvironment.getInstance().isPrintProgress()) {
log.log(Level.INFO, "Counting files in {0} ...", dir);
file_cnt = indexDown(sourceRoot, dir, true, 0, 0);
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO,
"Need to process: {0} files for {1}",
new Object[]{file_cnt, dir});
}
}
indexDown(sourceRoot, dir, false, 0, file_cnt);
while (uidIter != null && uidIter.term() != null
&& uidIter.term().utf8ToString().startsWith(startuid)) {
removeFile();
BytesRef next = uidIter.next();
if (next==null) {
uidIter=null;
}
}
} finally {
reader.close();
}
}
} finally {
if (writer != null) {
try {
writer.prepareCommit();
writer.commit();
writer.close();
} catch (IOException e) {
log.log(Level.WARNING, "An error occured while closing writer", e);
}
}
if (ctags != null) {
try {
ctags.close();
} catch (IOException e) {
log.log(Level.WARNING,
"An error occured while closing ctags process", e);
}
}
synchronized (lock) {
running = false;
}
}
if (!isInterrupted() && isDirty()) {
if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) {
optimize();
}
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
File timestamp = new File(env.getDataRootFile(), "timestamp");
String purpose = "used for timestamping the index database.";
if (timestamp.exists()) {
if (!timestamp.setLastModified(System.currentTimeMillis())) {
log.log(Level.WARNING, "Failed to set last modified time on ''{0}'', {1}",
new Object[]{timestamp.getAbsolutePath(), purpose});
}
} else {
if (!timestamp.createNewFile()) {
log.log(Level.WARNING, "Failed to create file ''{0}'', {1}",
new Object[]{timestamp.getAbsolutePath(), purpose});
}
}
}
}
|
diff --git a/WebAlbums3-Servlet/src/java/net/wazari/view/servlet/exchange/ViewSessionImpl.java b/WebAlbums3-Servlet/src/java/net/wazari/view/servlet/exchange/ViewSessionImpl.java
index ca698b55..0edb23da 100644
--- a/WebAlbums3-Servlet/src/java/net/wazari/view/servlet/exchange/ViewSessionImpl.java
+++ b/WebAlbums3-Servlet/src/java/net/wazari/view/servlet/exchange/ViewSessionImpl.java
@@ -1,670 +1,670 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.wazari.view.servlet.exchange;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.wazari.dao.entity.Theme;
import net.wazari.dao.entity.Utilisateur;
import net.wazari.dao.exchange.ServiceSession;
import net.wazari.service.exchange.ViewSession.Action;
import net.wazari.service.exchange.ViewSession.Special;
import net.wazari.service.exchange.ViewSessionAlbum.ViewSessionAlbumDisplay;
import net.wazari.service.exchange.ViewSessionAlbum.ViewSessionAlbumEdit;
import net.wazari.service.exchange.ViewSessionAlbum.ViewSessionAlbumSubmit;
import net.wazari.service.exchange.ViewSessionCarnet.ViewSessionCarnetDisplay;
import net.wazari.service.exchange.ViewSessionCarnet.ViewSessionCarnetEdit;
import net.wazari.service.exchange.ViewSessionCarnet.ViewSessionCarnetSubmit;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoDisplay;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoDisplay.ViewSessionPhotoDisplayMassEdit;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoDisplay.ViewSessionPhotoDisplayMassEdit.Turn;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoEdit;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoFastEdit;
import net.wazari.service.exchange.ViewSessionPhoto.ViewSessionPhotoSubmit;
import net.wazari.service.exchange.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author kevin
*/
public class ViewSessionImpl implements
ServiceSession,
ViewSessionLogin,
ViewSessionAlbum, ViewSessionAlbumDisplay, ViewSessionAlbumEdit, ViewSessionAlbumSubmit,
ViewSessionConfig,
ViewSessionPhoto, ViewSessionPhotoDisplay, ViewSessionPhotoEdit, ViewSessionPhotoSubmit,
ViewSessionTag,
ViewSessionImages, ViewSessionPhotoDisplayMassEdit, ViewSessionPhotoFastEdit,
ViewSessionCarnet, ViewSessionCarnetDisplay, ViewSessionCarnetEdit, ViewSessionCarnetSubmit,
ViewSessionDatabase,
ViewSessionMaint,
ViewSessionBenchmark{
private static final Logger log = LoggerFactory.getLogger(ViewSessionImpl.class.getCanonicalName());
private HttpServletRequest request;
private HttpServletResponse response;
private Integer DEFAULT_PHOTOALBUM_SIZE = 15;
public ViewSessionImpl(HttpServletRequest request, HttpServletResponse response, ServletContext context) {
this.request = request;
this.response = response;
}
@Override
public String getBirthdate() {
return getString("birthdate");
}
@Override
public String getContact() {
return getString("contact");
}
@Override
public String getDesc() {
return getString("desc");
}
@Override
public String getCarnetText() {
return getString("carnetText");
}
@Override
public String getNom() {
return getString("nom");
}
@Override
public String getDate() {
return getString("date");
}
@Override
public Integer[] getTags() {
return getIntArray("tags");
}
@Override
public Integer[] getNewTag() {
return getIntArray("newTag");
}
@Override
public boolean getForce() {
return "yes".equals(getString("force"));
}
@Override
public boolean getSuppr() {
String suppr = getString("suppr") ;
return "Oui je veux supprimer cette photo".equals(suppr) ||
"Oui je veux supprimer cet album".equals(suppr) ||
"Oui je veux supprimer ce carnet".equals(suppr);
}
@Override
public Integer getPage() {
return getInteger("page");
}
@Override
public Integer getNbPerYear() {
return getInteger("nbPerYear");
}
@Override
public Integer getUserAllowed() {
return getInteger("user");
}
@Override
public Special getSpecial() {
return getEnum("special", Special.class);
}
@Override
public Action getAction() {
return getEnum("action", Action.class);
}
@Override
public BenchAction getBenchAction() {
return getEnum("action", BenchAction.class);
}
@Override
public Mode getMode() {
return getEnum("mode", Mode.class);
}
@Override
public String getUserPass() {
return getString("userPass");
}
@Override
public String getUserName() {
return getString("userName") ;
}
@Override
public Boolean dontRedirect() {
return getBoolean("dontRedirect") ;
}
@Override
public boolean directFileAccess() {
String direct = getString("directFileAccess");
if (direct == null)
direct = getSessionObject("directFileAccess", String.class);
return "y".equals(direct);
}
@Override
public void setDirectFileAccess(boolean access) {
setSessionObject("directFileAccess", access ? "y" : "n");
}
/** ** **/
@Override
public Integer getThemeId() {
return getInteger("themeId");
}
@Override
public void setTheme(Theme enrTheme) {
setSessionObject("theme", enrTheme);
}
@Override
public Theme getTheme() {
return getSessionObject("theme", Theme.class);
}
/** ** **/
@Override
public File getTempDir() {
return getSessionObject("tempDir", File.class);
}
/** ** **/
@Override
public Utilisateur getUser() {
return getSessionObject("user", Utilisateur.class);
}
@Override
public void setUser(Utilisateur enrUser) {
setSessionObject("user", enrUser);
}
/** ** **/
@Override
public boolean isRootSession() {
Boolean val = getSessionObject("rootSession", Boolean.class);
if (val == null) {
val = false;
}
return val;
}
@Override
public void setRootSession(Boolean rootSession) {
setSessionObject("rootSession", rootSession);
}
/** ** **/
@Override
public boolean isSessionManager() {
Boolean ret = getSessionObject("sessionManager", Boolean.class);
if (ret == null) {
ret = false;
}
return ret;
}
@Override
public boolean isAdminSession() {
return this.getUser() != null && this.getUser().getId() == 1 ;
}
@Override
public void setSessionManager(Boolean sessionManager) {
setSessionObject("sessionManager", sessionManager);
}
/** ** **/
@Override
public Integer getId() {
return getInteger("id");
}
@Override
public Integer getCarnet() {
return getInteger("carnet");
}
@Override
public String getNouveau() {
return getString("nouveau");
}
@Override
public Integer getTag() {
return getInteger("tag");
}
@Override
public Integer getStars() {
return getInteger("stars");
}
@Override
public String getLng() {
return getString("lng");
}
@Override
public String getLat() {
return getString("lat");
}
@Override
public boolean getVisible() {
return "y".equals(getString("visible"));
}
@Override
public boolean getMinor() {
return "y".equals(getString("minor"));
}
@Override
public boolean getCompleteChoix() {
return "y".equals(getString("complete"));
}
@Override
public String getImportTheme() {
return getString("importTheme");
}
@Override
public Integer getType() {
return getInteger("type");
}
@Override
public Integer getWidth() {
return getInteger("width");
}
@Override
public boolean getRepresent() {
return "y".equals(getString("represent"));
}
@Override
public boolean getThemeBackground() {
return "y".equals(getString("themeBackground"));
}
@Override
public boolean getThemePicture() {
return "y".equals(getString("themePicture"));
}
@Override
public Integer getTagPhoto() {
return getInteger("tagPhoto");
}
@Override
public Turn getTurn() {
return getEnum("turn", Turn.class);
}
@Override
public Integer getAddTag() {
return getInteger("addTag");
}
@Override
public boolean getChk(Integer id) {
return "modif".equals(getString("chk" + id));
}
@Override
public String getGpxDescr(Integer id) {
return getString("gpx_descr_" + id);
}
@Override
public Integer getRmTag() {
return getInteger("rmTag");
}
@Override
public Integer getAlbum() {
return getInteger("album");
}
@Override
public Integer getAlbmPage() {
return getInteger("albmPage");
}
@Override
public Integer[] getTagAsked() {
return getIntArray("tagAsked");
}
@Override
public boolean getWantTagChildren() {
return getString("wantTagChildren") != null;
}
@Override
public ImgMode getImgMode() {
return getEnum("mode", ImgMode.class);
}
@Override
public Configuration getConfiguration() {
return ConfigurationXML.getConf();
}
@Override
public void setContentDispositionFilename(String name) {
response.addHeader("Content-Disposition", "filename="+name);
}
@Override
public void setContentLength(int contentLength) {
response.setContentLength(contentLength);
}
@Override
public void setContentType(String type) {
response.setContentType(type);
}
@Override
public OutputStream getOutputStream() throws IOException {
return response.getOutputStream();
}
@Override
public Integer getParentTag() {
return getInteger("parentTag") ;
}
@Override
public Integer[] getSonTags() {
return getIntArray("sonTag") ;
}
private Set<Integer> splitInt(String in) {
if (in == null || in.length() == 1)
return new HashSet<Integer>();
Set<Integer> out = new HashSet<Integer>();
for (String str : in.split("-")) {
try {
out.add(Integer.parseInt(str));
} catch (NumberFormatException e) {
log.warn("Invalide number during split int:"+str);
}
}
return out ;
}
@Override
public Set<Integer> getCarnetPhoto() {
return splitInt(getString("carnetPhoto")) ;
}
@Override
public Set<Integer> getCarnetAlbum() {
return splitInt(getString("carnetAlbum")) ;
}
@Override
public Integer getCarnetRepr() {
return getInteger("carnetRepr") ;
}
@Override
public Integer getBorderWidth() {
return getInteger("borderWidth") ;
}
@Override
public String getBorderColor() {
return getString("borderColor") ;
}
/** ** ** ** **/
private Integer getInteger(String name) {
return getObject(name, Integer.class);
}
private String getString(String name) {
return getObject(name, String.class);
}
private Boolean getBoolean(String name) {
return getObject(name, Boolean.class);
}
private <T extends Enum<T>> T getEnum(String value, Class<T> type) {
return getObject(value, type);
}
private Integer[] getIntArray(String key) {
return castToIntArray(getParamArray(key));
}
private String[] getParamArray(String name) {
String[] ret = request.getParameterValues(name);
log.info( "getParamArray param:{} returned {}", new Object[]{name, Arrays.toString(ret)});
return ret;
}
private Integer[] castToIntArray(String[] from) {
if (from == null) {
return new Integer[]{};
}
ArrayList<Integer> ret = new ArrayList<Integer>(from.length);
for (int i = 0; i < from.length; i++) {
try {
ret.add(Integer.parseInt(from[i]));
} catch (NumberFormatException e) {
}
}
return ret.toArray(new Integer[0]);
}
@Override
public boolean isAuthenticated() {
return getUserPrincipal() != null;
}
@Override
public Principal getUserPrincipal() {
return request.getUserPrincipal();
}
@Override
public void login(String user, String passwd) {
try {
request.login(user, passwd);
} catch (ServletException ex) {
log.warn("ServletException", ex);
}
}
@Override
public ViewSessionPhotoDisplayMassEdit getMassEdit() {
return (ViewSessionPhotoDisplayMassEdit) this;
}
@Override
public MaintAction getMaintAction() {
return getObject("action", MaintAction.class);
}
@Override
public TagAction getTagAction() {
return getObject("tagAction", TagAction.class);
}
@Override
public Integer getCarnetsPage() {
return getInteger("carnetsPage") ;
}
@Override
public int getPhotoAlbumSize() {
Integer size = getInteger("photoAlbumSize");
if (size == null)
size = getSessionObject("photoAlbumSize", Integer.class);
if (size == null)
size = DEFAULT_PHOTOALBUM_SIZE;
return size;
}
@Override
public void setPhotoAlbumSize(int size) {
setSessionObject("photoAlbumSize", size);
}
@Override
public boolean getStatic() {
return "y".equals(getSessionObject("static", String.class));
}
@Override
public void setStatic(boolean statik) {
setSessionObject("static", statik ? "y" : "n");
}
private void setSessionObject(String string, Object value) {
setSessionObject(string, value, request.getSession());
}
private <T> T getObject(String string, Class<T> aClass) {
return getObject(string, aClass, request) ;
}
private <T> T getSessionObject(String key, Class<T> aClass) {
return getSessionObject(key, aClass, request.getSession(), request) ;
}
private static <T> T getObject(String name, Class<T> type, HttpServletRequest request) {
T ret = null;
String val = request.getParameter(name);
try {
if (val == null) {
ret = null ;
} else if (type == String.class) {
ret = type.cast(val);
} else if (type == Integer.class) {
ret = type.cast(Integer.parseInt(val));
} else if (type == Boolean.class) {
ret = type.cast(Boolean.parseBoolean(val));
} else if (type.isEnum()) {
ret = (T) Enum.valueOf((Class) type, val);
} else {
log.info( "Unknown class {} for parameter {}", new Object[]{type, name});
}
} catch (ClassCastException e) {
- log.info( "Can''t cast value {} into class {}", new Object[]{val, type});
+ log.warn( "Can''t cast value {} into class {}", new Object[]{val, type});
} catch (NullPointerException e) {
- log.info( "NullPointerException with {} for class {} ({})", new Object[]{val, type, name});
+ log.warn( "NullPointerException with {} for class {} ({})", new Object[]{val, type, name});
} catch (NumberFormatException e) {
- log.info( "NumberFormatException with '{}' for class {} ({})", new Object[]{val, type, name});
+ log.warn( "NumberFormatException with '{}' for class {} ({})", new Object[]{val, type, name});
} catch (IllegalArgumentException e) {
- log.info( "IllegalArgumentException with {} for class {}", new Object[]{val, type});
+ log.warn( "IllegalArgumentException with {} for class {}", new Object[]{val, type});
}
log.debug( "getObject param:{} type:{} returned {}", new Object[]{name, type, ret});
return ret;
}
private static <T> T getSessionObject(String name, Class<T> type, HttpSession session, HttpServletRequest request) {
T ret = type.cast(session.getAttribute(name));
if (ret == null && request != null) {
ret = getObject(name, type, request);
}
log.debug( "getSessionObject param:{} type:{} returned {}", new Object[]{name, type, ret});
return ret;
}
private static void setSessionObject(String key, Object val, HttpSession session) {
log.info( "setSessionObject param:{} val:{}", new Object[]{key, val});
session.setAttribute(key, val);
}
@Override
public String getDroit() {
return getString("user") ;
}
@Override
public boolean isRemoteAccess() {
log.info( "local: {}", request.getLocalAddr()) ;
log.info( "remote: {}", request.getRemoteAddr()) ;
return !request.getLocalAddr().equals(request.getRemoteHost()) ;
}
@Override
public void redirect(String filepath) {
try {
response.sendRedirect(filepath);
} catch (IOException ex) {
log.error("IOException", ex);
}
}
public static class ViewSessionLoginImpl implements ViewSessionSession {
private HttpSession session ;
public ViewSessionLoginImpl (HttpSession session) {
this.session = session ;
}
@Override
public void setTempDir(File temp) {
setSessionObject("tempDir", temp, session);
}
@Override
public File getTempDir() {
return ViewSessionImpl.getSessionObject("tempDir", File.class, session, null) ;
}
@Override
public Configuration getConfiguration() {
return ConfigurationXML.getConf() ;
}
}
}
| false | true | private static <T> T getObject(String name, Class<T> type, HttpServletRequest request) {
T ret = null;
String val = request.getParameter(name);
try {
if (val == null) {
ret = null ;
} else if (type == String.class) {
ret = type.cast(val);
} else if (type == Integer.class) {
ret = type.cast(Integer.parseInt(val));
} else if (type == Boolean.class) {
ret = type.cast(Boolean.parseBoolean(val));
} else if (type.isEnum()) {
ret = (T) Enum.valueOf((Class) type, val);
} else {
log.info( "Unknown class {} for parameter {}", new Object[]{type, name});
}
} catch (ClassCastException e) {
log.info( "Can''t cast value {} into class {}", new Object[]{val, type});
} catch (NullPointerException e) {
log.info( "NullPointerException with {} for class {} ({})", new Object[]{val, type, name});
} catch (NumberFormatException e) {
log.info( "NumberFormatException with '{}' for class {} ({})", new Object[]{val, type, name});
} catch (IllegalArgumentException e) {
log.info( "IllegalArgumentException with {} for class {}", new Object[]{val, type});
}
log.debug( "getObject param:{} type:{} returned {}", new Object[]{name, type, ret});
return ret;
}
| private static <T> T getObject(String name, Class<T> type, HttpServletRequest request) {
T ret = null;
String val = request.getParameter(name);
try {
if (val == null) {
ret = null ;
} else if (type == String.class) {
ret = type.cast(val);
} else if (type == Integer.class) {
ret = type.cast(Integer.parseInt(val));
} else if (type == Boolean.class) {
ret = type.cast(Boolean.parseBoolean(val));
} else if (type.isEnum()) {
ret = (T) Enum.valueOf((Class) type, val);
} else {
log.info( "Unknown class {} for parameter {}", new Object[]{type, name});
}
} catch (ClassCastException e) {
log.warn( "Can''t cast value {} into class {}", new Object[]{val, type});
} catch (NullPointerException e) {
log.warn( "NullPointerException with {} for class {} ({})", new Object[]{val, type, name});
} catch (NumberFormatException e) {
log.warn( "NumberFormatException with '{}' for class {} ({})", new Object[]{val, type, name});
} catch (IllegalArgumentException e) {
log.warn( "IllegalArgumentException with {} for class {}", new Object[]{val, type});
}
log.debug( "getObject param:{} type:{} returned {}", new Object[]{name, type, ret});
return ret;
}
|
diff --git a/source/src/net/grinder/engine/process/instrumenter/dcr/RecorderLocator.java b/source/src/net/grinder/engine/process/instrumenter/dcr/RecorderLocator.java
index 86e76e1f..f1669fa4 100644
--- a/source/src/net/grinder/engine/process/instrumenter/dcr/RecorderLocator.java
+++ b/source/src/net/grinder/engine/process/instrumenter/dcr/RecorderLocator.java
@@ -1,222 +1,222 @@
// Copyright (C) 2009 Philip Aston
// All rights reserved.
//
// This file is part of The Grinder software distribution. Refer to
// the file LICENSE which is part of The Grinder distribution for
// licensing details. The Grinder distribution is available on the
// Internet at http://grinder.sourceforge.net/
//
// 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 net.grinder.engine.process.instrumenter.dcr;
import static extra166y.CustomConcurrentHashMap.IDENTITY;
import static extra166y.CustomConcurrentHashMap.STRONG;
import static extra166y.CustomConcurrentHashMap.WEAK;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import net.grinder.common.UncheckedGrinderException;
import net.grinder.engine.common.EngineException;
import net.grinder.engine.process.ScriptEngine.Recorder;
import extra166y.CustomConcurrentHashMap;
/**
* Static methods that weaved code uses to dispatch enter and exit calls to the
* appropriate {@link Recorder}.
*
* @author Philip Aston
* @version $Revision:$
*/
public final class RecorderLocator implements RecorderRegistry {
private static final RecorderLocator s_instance = new RecorderLocator();
/**
* Accessor for the unit tests.
*/
static void clearRecorders() {
s_instance.m_recorders.clear();
}
/**
* Target reference -> location -> recorder list. Location strings are
* interned, so we use an identity hash map for both maps. We use concurrent
* structures throughout to avoid synchronisation. The target reference is the
* first key to minimise the cost of traversing woven code for
* non-instrumented references, which is important if {@code Object}, {@code
* PyObject}, etc. are instrumented.
*/
private final ConcurrentMap<Object,
ConcurrentMap<String, List<Recorder>>>
m_recorders =
new CustomConcurrentHashMap<Object,
ConcurrentMap<String, List<Recorder>>>(
WEAK, IDENTITY, STRONG, IDENTITY, 101);
private List<Recorder> getRecorderList(Object target,
String locationID) {
final ConcurrentMap<String, List<Recorder>> locationMap =
m_recorders.get(target);
if (locationMap != null) {
final List<Recorder> list = locationMap.get(locationID);
if (list != null) {
return list;
}
}
return Collections.<Recorder>emptyList();
}
/**
* Called when a weaved method is entered.
*
* @param target
* The reference used to call the method. The class is used for
* static methods or constructors.
* @param location
* Unique identity generated when the method was instrumented.
* Will be interned.
* @throws EngineException
*/
public static void enter(Object target, String location) {
if (target == null) {
// We don't allow recorders to register for a null target,
// but weaved code can be called with null.
return;
}
// Beware when enabling the following logging - calls on the object itself
// may fail subtly.
// System.out.printf("enter(%s, %s, %s)%n",
// System.identityHashCode(target),
// target.getClass(),
// location);
try {
for (Recorder recorder : s_instance.getRecorderList(target, location)) {
// System.out.printf(" -> %s%n", System.identityHashCode(recorder));
recorder.start();
}
}
catch (EngineException e) {
throw new RecordingFailureException(e);
}
}
/**
* Called when a weaved method is exited.
*
* @param target
* The reference used to call the method. The class is used for
* static methods or constructors.
* @param location
* Unique identity generated when the method was instrumented.
* Will be interned.
* @param success
* {@code true} if the exit was a normal return, {code false} if an
* exception was thrown.
*/
public static void exit(Object target, String location, boolean success) {
if (target == null) {
// We don't allow recorders to register for a null target,
// but weaved code can be called with null.
return;
}
// Beware when enabling the following logging - calls on the object itself
// may fail subtly.
// System.out.printf("exit(%s, %s, %s, %s)%n",
-// System.identityHashCode(target.hashCode()),
+// System.identityHashCode(target),
// target.getClass(),
// location,
// success);
final List<Recorder> recorders =
s_instance.getRecorderList(target, location);
// Iterate over recorders in reverse.
final ListIterator<Recorder> i = recorders.listIterator(recorders.size());
try {
while (i.hasPrevious()) {
final Recorder recorder = i.previous();
// System.out.printf(" -> %s%n", System.identityHashCode(recorder));
recorder.end(success);
}
}
catch (EngineException e) {
throw new RecordingFailureException(e);
}
}
/**
* Expose our registry to the package.
*
* @return The registry.
*/
static RecorderRegistry getRecorderRegistry() {
return s_instance;
}
/**
* {@inheritDoc}.
*/
public void register(Object target, String location, Recorder recorder) {
// We will create and quickly discard many maps and lists here to avoid
// needing to lock the ConcurrentMaps. It is important that the
// enter/exit methods are lock free, the instrumentation registration
// process can be relatively slow.
final ConcurrentMap<String, List<Recorder>> newMap =
new CustomConcurrentHashMap<String, List<Recorder>>(
STRONG, IDENTITY, STRONG, IDENTITY, 0);
final ConcurrentMap<String, List<Recorder>> oldMap =
m_recorders.putIfAbsent(target, newMap);
final ConcurrentMap<String, List<Recorder>> locationMap =
oldMap != null ? oldMap : newMap;
final List<Recorder> newList = new CopyOnWriteArrayList<Recorder>();
final List<Recorder> oldList =
locationMap.putIfAbsent(location.intern(), newList);
(oldList != null ? oldList : newList).add(recorder);
}
private static final class RecordingFailureException
extends UncheckedGrinderException {
private RecordingFailureException(EngineException cause) {
super("Recording Failure", cause);
}
}
}
| true | true | public static void exit(Object target, String location, boolean success) {
if (target == null) {
// We don't allow recorders to register for a null target,
// but weaved code can be called with null.
return;
}
// Beware when enabling the following logging - calls on the object itself
// may fail subtly.
// System.out.printf("exit(%s, %s, %s, %s)%n",
// System.identityHashCode(target.hashCode()),
// target.getClass(),
// location,
// success);
final List<Recorder> recorders =
s_instance.getRecorderList(target, location);
// Iterate over recorders in reverse.
final ListIterator<Recorder> i = recorders.listIterator(recorders.size());
try {
while (i.hasPrevious()) {
final Recorder recorder = i.previous();
// System.out.printf(" -> %s%n", System.identityHashCode(recorder));
recorder.end(success);
}
}
catch (EngineException e) {
throw new RecordingFailureException(e);
}
}
| public static void exit(Object target, String location, boolean success) {
if (target == null) {
// We don't allow recorders to register for a null target,
// but weaved code can be called with null.
return;
}
// Beware when enabling the following logging - calls on the object itself
// may fail subtly.
// System.out.printf("exit(%s, %s, %s, %s)%n",
// System.identityHashCode(target),
// target.getClass(),
// location,
// success);
final List<Recorder> recorders =
s_instance.getRecorderList(target, location);
// Iterate over recorders in reverse.
final ListIterator<Recorder> i = recorders.listIterator(recorders.size());
try {
while (i.hasPrevious()) {
final Recorder recorder = i.previous();
// System.out.printf(" -> %s%n", System.identityHashCode(recorder));
recorder.end(success);
}
}
catch (EngineException e) {
throw new RecordingFailureException(e);
}
}
|
diff --git a/src/UploadHandler.java b/src/UploadHandler.java
index 4879f80..56e94d3 100755
--- a/src/UploadHandler.java
+++ b/src/UploadHandler.java
@@ -1,19 +1,19 @@
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.FileInputStream;
public class UploadHandler extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/xml;charset=UTF-8");
FileInputStream stream = new FileInputStream(request.getAttribute("file").toString());
- new CombinedIndexer().index(request.getParameter("file"), stream, request.getParameter("id"), request.getParameter("text"));
+ new CombinedIndexer().index(request.getParameter("identifier"), stream, request.getParameter("id"), request.getParameter("text"));
response.setStatus(HttpServletResponse.SC_OK);
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/xml;charset=UTF-8");
FileInputStream stream = new FileInputStream(request.getAttribute("file").toString());
new CombinedIndexer().index(request.getParameter("file"), stream, request.getParameter("id"), request.getParameter("text"));
response.setStatus(HttpServletResponse.SC_OK);
}
| public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/xml;charset=UTF-8");
FileInputStream stream = new FileInputStream(request.getAttribute("file").toString());
new CombinedIndexer().index(request.getParameter("identifier"), stream, request.getParameter("id"), request.getParameter("text"));
response.setStatus(HttpServletResponse.SC_OK);
}
|
diff --git a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/FlexoModelObject.java b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/FlexoModelObject.java
index f527ecde2..7c8465595 100644
--- a/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/FlexoModelObject.java
+++ b/flexodesktop/model/flexofoundation/src/main/java/org/openflexo/foundation/FlexoModelObject.java
@@ -1,1400 +1,1400 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.foundation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openflexo.foundation.action.AddFlexoProperty;
import org.openflexo.foundation.action.DeleteFlexoProperty;
import org.openflexo.foundation.action.FlexoActionType;
import org.openflexo.foundation.action.FlexoActionizer;
import org.openflexo.foundation.action.FlexoActionnable;
import org.openflexo.foundation.action.SortFlexoProperties;
import org.openflexo.foundation.ontology.EditionPatternInstance;
import org.openflexo.foundation.ontology.EditionPatternReference;
import org.openflexo.foundation.rm.FlexoProject;
import org.openflexo.foundation.rm.ScreenshotResource;
import org.openflexo.foundation.utils.FlexoDocFormat;
import org.openflexo.foundation.utils.FlexoModelObjectReference;
import org.openflexo.foundation.validation.Validable;
import org.openflexo.foundation.viewpoint.EditionPattern;
import org.openflexo.foundation.viewpoint.PatternRole;
import org.openflexo.foundation.wkf.dm.WKFAttributeDataModification;
import org.openflexo.inspector.model.TabModel;
import org.openflexo.localization.FlexoLocalization;
import org.openflexo.localization.Language;
import org.openflexo.logging.FlexoLogger;
import org.openflexo.toolbox.HTMLUtils;
import org.openflexo.ws.client.PPMWebService.PPMObject;
import org.openflexo.xmlcode.StringEncoder;
import org.openflexo.xmlcode.XMLMapping;
/**
* Abstract class for all objects involved in FLEXO model definition
*
* @author sguerin
*
*/
public abstract class FlexoModelObject extends FlexoXMLSerializableObject implements FlexoActionnable {
public static boolean stringHasChanged(String old, String newString) {
return old == null && newString != null || old != null && !old.equals(newString);
}
private static final Logger logger = FlexoLogger.getLogger(FlexoModelObject.class.getPackage().toString());
public static final String ID_SEPARATOR = "_";
public static final Comparator<FlexoModelObject> DEFAULT_COMPARATOR = new FlexoDefaultComparator<FlexoModelObject>();
public static final Comparator<FlexoModelObject> NAME_COMPARATOR = new FlexoNameComparator<FlexoModelObject>();
private long flexoID = -2;
private transient Object _context;
private FlexoDocFormat docFormat;
private static String currentUserIdentifier;
private boolean isRegistered = false;
private Map<String, String> specificDescriptions;
private Vector<FlexoProperty> customProperties;
public static FlexoActionizer<AddFlexoProperty, FlexoModelObject, FlexoModelObject> addFlexoPropertyActionizer;
public static FlexoActionizer<DeleteFlexoProperty, FlexoProperty, FlexoProperty> deleteFlexoPropertyActionizer;
public static FlexoActionizer<SortFlexoProperties, FlexoModelObject, FlexoModelObject> sortFlexoPropertiesActionizer;
private boolean hasSpecificDescriptions = false;
private Vector<FlexoModelObjectReference<?>> referencers;
// Imported objects
private boolean isDeletedOnServer = false;
private String uri;
private String versionURI;
private String uriFromSourceObject;
public static String getCurrentUserIdentifier() {
if (currentUserIdentifier == null) {
currentUserIdentifier = "FLX".intern();
}
return currentUserIdentifier;
}
public static void setCurrentUserIdentifier(String aUserIdentifier) {
if (aUserIdentifier != null && aUserIdentifier.indexOf('#') > -1) {
aUserIdentifier = aUserIdentifier.replace('#', '-');
FlexoModelObject.currentUserIdentifier = aUserIdentifier.intern();
}
}
private String userIdentifier;
public String getUserIdentifier() {
if (userIdentifier == null) {
return getCurrentUserIdentifier();
}
return userIdentifier;
}
public void setUserIdentifier(String aUserIdentifier) {
if (aUserIdentifier != null && aUserIdentifier.indexOf('#') > -1) {
aUserIdentifier = aUserIdentifier.replace('#', '-');
}
userIdentifier = aUserIdentifier != null ? aUserIdentifier.intern() : null;
if (!isDeserializing()) {
fireSerializationIdChanged();
}
}
/**
* Constructor used by Serializable. <blockquote> The deserialization process does not use the object's constructor - the object is
* instantiated without a constructor and initialized using the serialized instance data. The only requirement on the constructor for a
* class that implements Serializable is that the first non-serializable superclass in its inheritence hierarchy must have a no-argument
* constructor. <BR>
* From <a
* href="http://www.jguru.com/faq/view.jsp?EID=251942">http://www.jguru.com/faq/view.jsp?EID=251942</A></blockquote>
*/
public FlexoModelObject() {
this(null);
}
/**
*
*/
public FlexoModelObject(FlexoProject project) {
super();
referencers = new Vector<FlexoModelObjectReference<?>>();
specificDescriptions = new TreeMap<String, String>();
customProperties = new Vector<FlexoProperty>();
_editionPatternReferences = new Vector<EditionPatternReference>();
registerObject(project);
}
protected void registerObject(FlexoProject project) {
if (project != null) {
/*
* if (project.getLastUniqueIDHasBeenSet() && flexoID < 0) { flexoID = project.getNewFlexoID();
* System.err.println("Via constructor New flexo ID: "+flexoID); }
*/
project.register(this);
isRegistered = true;
} else {
if (logger != null && logger.isLoggable(Level.FINE) && !(this instanceof TemporaryFlexoModelObject)) {
logger.fine("No project for object of type " + getClassNameKey());
}
}
}
public FlexoModelObject(FlexoProject project, String description) {
this(project);
this.description = description;
}
/**
* Overrides getStringEncoder
*
* @see org.openflexo.foundation.FlexoXMLSerializableObject#getStringEncoder()
*/
@Override
public StringEncoder getStringEncoder() {
if (getProject() != null) {
return getProject().getStringEncoder();
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("No project, using the default string encoder. Any elements related to a FlexoProject like BindingValues or DMType will fail to be converted");
}
return super.getStringEncoder();
}
}
public FlexoProject getProject() {
if (getXMLResourceData() != null && getXMLResourceData().getFlexoResource() != null) {
return getXMLResourceData().getFlexoResource().getProject();
}
return null;
}
@Override
public XMLMapping getXMLMapping() {
if (getXMLResourceData() != null) {
return getXMLResourceData().getXMLMapping();
}
return null;
}
public boolean isDeletedOnServer() {
return isDeletedOnServer;
}
public void setIsDeletedOnServer(boolean isDeletedOnServer) {
if (this.isDeletedOnServer == isDeletedOnServer) {
return;
}
this.isDeletedOnServer = isDeletedOnServer;
setChanged();
notifyObservers(new DataModification("isDeletedOnServer", !this.isDeletedOnServer, isDeletedOnServer));
}
public void markAsDeletedOnServer() {
setIsDeletedOnServer(true);
}
public void copyObjectAttributesInto(PPMObject object) {
object.setName(getName());
object.setUri(getURI());
object.setVersionUri(getVersionURI());
object.setGeneralDescription(getDescription());
object.setBusinessDescription(getBusinessDescription());
object.setTechnicalDescription(getTechnicalDescription());
object.setUserManualDescription(getUserManualDescription());
}
protected void updateFromObject(PPMObject object) {
setIsDeletedOnServer(false);
setURI(object.getUri());
setVersionURI(object.getVersionUri());
setDescription(object.getGeneralDescription());
setBusinessDescription(object.getBusinessDescription());
setTechnicalDescription(object.getTechnicalDescription());
setUserManualDescription(object.getUserManualDescription());
try {
setName(object.getName());
} catch (Exception e) {
if (logger.isLoggable(Level.SEVERE)) {
logger.log(Level.SEVERE, "setName threw an exception on " + this + "! This should never happen for imported objects", e);
}
}
}
/**
* Returns wheter this object is imported or not. Object implementing FlexoImportableObject should override this method
*
* @return true if this object is imported.
*/
public boolean isImported() {
return false;
}
public Class<? extends PPMObject> getEquivalentPPMClass() {
return null;
}
protected boolean isEquivalentTo(PPMObject object) {
if (object == null) {
return false;
}
if (isDeletedOnServer()) {
return false;
}
if (getEquivalentPPMClass() != object.getClass()) {
return false;
}
if (stringHasChanged(getName(), object.getName())) {
return false;
}
if (stringHasChanged(getURI(), object.getUri())) {
return false;
}
if (stringHasChanged(getVersionURI(), object.getVersionUri())) {
return false;
}
if (stringHasChanged(getDescription(), object.getGeneralDescription())) {
return false;
}
if (stringHasChanged(getBusinessDescription(), object.getBusinessDescription())) {
return false;
}
if (stringHasChanged(getTechnicalDescription(), object.getTechnicalDescription())) {
return false;
}
if (stringHasChanged(getUserManualDescription(), object.getUserManualDescription())) {
return false;
}
return true;
}
public static <O extends FlexoModelObject> O getObjectWithURI(Vector<O> objects, String uri) {
for (O o : objects) {
if (o.getURI().equals(uri)) {
return o;
}
}
return null;
}
public String getURI() {
if (getProject() == null) {
throw new RuntimeException("Project is undefined for object " + getClass().getName());
}
if (isImported() || uri != null) {
return uri;
}
if (isSerializing()) {
return null; // We never serialize URI for unimported objects
}
return getProject().getURI() + "fmo/" + getClass().getSimpleName() + getUserIdentifier() + "_" + getFlexoID();
}
public void setURI(String uri) {
this.uri = uri;
}
public String getVersionURI() {
if (getProject() == null) {
throw new RuntimeException("Project is undefined for object " + getClass().getName());
}
if (isImported() || versionURI != null) {
return versionURI;
}
if (isSerializing()) {
return null; // We never serialize URI for unimported objects
}
return getProject().getProjectVersionURI() + "/fmo/version_of_" + getClass().getSimpleName() + getUserIdentifier() + "_"
+ getFlexoID();
}
public void setVersionURI(String versionURI) {
this.versionURI = versionURI;
}
public String getURIFromSourceObject() {
return uriFromSourceObject;
}
public void setURIFromSourceObject(String uri) {
this.uriFromSourceObject = uri;
}
public abstract String getFullyQualifiedName();
private String name;
public String getName() {
return name;
}
public void setName(String name) throws Exception {
String old = this.name;
this.name = name;
if (!isDeserializing()) {
setChanged();
notifyObservers(new NameChanged(old, this.name));
}
}
/**
* Returns a displayable name that is localized and readable by a user. This method is final because you should rather override
* {@link #getName()} or {@link #getClassNameKey()}
*
* @return a displayable name that is localized and readable by a user.
*/
public final String getDisplayableName() {
if (getName() != null) {
return getLocalizedClassName() + " " + getName();
} else {
return FlexoLocalization.localizedForKey("a") + " " + getLocalizedClassName();
}
}
public String getDisplayableDescription() {
return getDisplayableName();
}
/**
* @return
*/
public String getLocalizedClassName() {
return FlexoLocalization.localizedForKey(getClassNameKey());
}
/**
* @return Returns the flexoID.
*/
public long getFlexoID() {
if (isBeingCloned()) {
return -1;
}
if (getProject() != null) {
if (getProject().getLastUniqueIDHasBeenSet() && flexoID < 0 && !isDeserializing()) {
flexoID = getProject().getNewFlexoID();
// setChanged();
}
if (!isRegistered) {
getProject().register(this);
isRegistered = true;
}
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("No project for object of type " + getClassNameKey());
}
}
return flexoID;
}
/**
* @param flexoID
* The flexoID to set.
*/
public void setFlexoID(long flexoID) {
if (!isCreatedByCloning() && flexoID > 0 && flexoID != this.flexoID) {
this.flexoID = flexoID;
if (!isDeserializing()) {
setChanged();
notifyObservers(new DataModification("flexoID", new Long(this.flexoID), new Long(flexoID)));
fireSerializationIdChanged();
}
}
if (flexoID < 0 && !isCreatedByCloning() && !(this instanceof FlexoProject) && getXMLResourceData() != null) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Tried to set a negative ID on object of class " + getClass().getName());
}
}
}
private void fireSerializationIdChanged() {
for (FlexoModelObjectReference ref : new Vector<FlexoModelObjectReference>(referencers)) {
ref.notifySerializationIdHasChanged();
}
}
public String getSerializationIdentifier() {
return getSerializationIdentifier(getUserIdentifier(), String.valueOf(getFlexoID()));
}
public static String getSerializationIdentifier(String userIdentifier, String flexoId) {
return userIdentifier + ID_SEPARATOR + flexoId;
}
/**
* A map that stores the different declared actions for each class
*/
private static final Map<Class, List<FlexoActionType<?, ?, ?>>> _declaredActionsForClass = new Hashtable<Class, List<FlexoActionType<?, ?, ?>>>();
/**
* A map that stores all the actions for each class (computed with the inheritance of each class)
*/
private static final Hashtable<Class, List<FlexoActionType<?, ?, ?>>> _actionListForClass = new Hashtable<Class, List<FlexoActionType<?, ?, ?>>>();
public List<FlexoActionType<?, ?, ?>> getActionList() {
return getActionList(getClass());
}
public static <T extends FlexoModelObject> List<FlexoActionType<?, ?, ?>> getActionList(Class<T> aClass) {
if (_actionListForClass.get(aClass) == null) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("COMPUTE ACTION_LIST FOR " + aClass.getName());
}
List<FlexoActionType<?, ?, ?>> returned = updateActionListFor(aClass);
if (logger.isLoggable(Level.FINE)) {
logger.fine("DONE. COMPUTE ACTION_LIST FOR " + aClass.getName() + ": " + returned.size() + " action(s) :");
for (FlexoActionType<?, ?, ?> next : returned) {
logger.fine(" " + next.getLocalizedName());
}
logger.fine(".");
}
return returned;
}
List<FlexoActionType<?, ?, ?>> returned = _actionListForClass.get(aClass);
if (logger.isLoggable(Level.FINE)) {
logger.fine("RETURN (NO COMPUTING) ACTION_LIST FOR " + aClass.getName() + ": " + returned.size() + " action(s) :");
for (FlexoActionType<?, ?, ?> next : returned) {
logger.fine(" " + next.getLocalizedName());
}
logger.fine(".");
}
return returned;
}
public static <T1 extends FlexoModelObject, T extends T1> void addActionForClass(FlexoActionType<?, T1, ?> actionType,
Class<T> objectClass) {
if (logger.isLoggable(Level.FINE)) {
logger.fine("addActionForClass: " + actionType + " for " + objectClass);
}
List<FlexoActionType<?, ?, ?>> actions = _declaredActionsForClass.get(objectClass);
if (actions == null) {
actions = new ArrayList<FlexoActionType<?, ?, ?>>();
_declaredActionsForClass.put(objectClass, actions);
}
if (actionType != null) {
if (!actions.contains(actionType)) {
actions.add(actionType);
}
} else {
logger.warning("Trying to declare null action !");
}
if (_actionListForClass != null) {
Vector<Class> entriesToRemove = new Vector<Class>();
for (Class aClass : _actionListForClass.keySet()) {
if (objectClass.isAssignableFrom(aClass)) {
entriesToRemove.add(aClass);
}
}
for (Class aClass : entriesToRemove) {
logger.info("Recompute actions list for " + aClass);
_actionListForClass.remove(aClass);
}
}
}
private static <T extends FlexoModelObject> List<FlexoActionType<?, ?, ?>> updateActionListFor(Class<T> aClass) {
List<FlexoActionType<?, ?, ?>> newActionList = new Vector<FlexoActionType<?, ?, ?>>();
for (Map.Entry<Class, List<FlexoActionType<?, ?, ?>>> e : _declaredActionsForClass.entrySet()) {
if (e.getKey().isAssignableFrom(aClass)) {
newActionList.addAll(e.getValue());
}
}
_actionListForClass.put(aClass, newActionList);
if (logger.isLoggable(Level.FINE)) {
logger.fine("updateActionListFor() class: " + aClass);
for (FlexoActionType a : newActionList) {
logger.finer(" > " + a);
}
}
return newActionList;
}
@Override
public int getActionCount() {
return getActionList().size();
}
@Override
public FlexoActionType<?, ?, ?> getActionTypeAt(int index) {
return getActionList().get(index);
}
public void delete() {
// if (logger.isLoggable(Level.FINE)) logger.fine ("Delete
// "+this.getClass().getName()+" : "+this);
if (isDeleted) {
// in some case : the delete may be called twice on a sequence (in case of deletion of last widget of the sequence)...
// and it will fail
// a good idea would be to avoid this double invocation.
// In the mean time, this little hack will do the trick.
return;
}
isDeleted = true;
if (getProject() != null) {
if (isRegistered) {
getProject().unregister(this);
}
isRegistered = false;
} else {
if (logger.isLoggable(Level.WARNING)) {
- logger.warning("Project is null for " + this);
+ logger.warning("Project is null for " + this.getClass().getSimpleName() + "_" + this.getFlexoID());
}
}
for (EditionPatternReference ref : new ArrayList<EditionPatternReference>(getEditionPatternReferences())) {
if (ref.getEditionPatternInstance() != null) {
ref.getEditionPatternInstance().nullifyPatternActor(ref.getPatternRole());
}
ref.delete();
}
_editionPatternReferences.clear();
_editionPatternReferences = null;
for (FlexoModelObjectReference ref : new ArrayList<FlexoModelObjectReference>(referencers)) {
ref.notifyObjectDeletion();
}
referencers.clear();
referencers = null;
setChanged();
notifyObservers(new ObjectDeleted(this));
if (getProject() != null) {
getProject().notifyObjectDeleted(this);
}
}
@Override
public String getDeletedProperty() {
return DELETED_PROPERTY;
}
public void undelete() {
// if (logger.isLoggable(Level.FINE)) logger.fine ("Delete
// "+this.getClass().getName()+" : "+this);
if (getProject() != null) {
if (isRegistered) {
getProject().register(this);
}
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Project is null for " + this);
}
}
isDeleted = false;
referencers = new Vector<FlexoModelObjectReference<?>>();
setChanged();
if (getProject() != null) {
getProject().notifyObjectCreated(this);
}
}
public boolean isDeleted() {
return isDeleted;
}
protected boolean isDeleted = false;
private boolean dontGenerate = false;
private String description;
public Object getContext() {
return _context;
}
public void setContext(Object context) {
_context = context;
}
/**
*
*/
public boolean getDontEscapeLatex() {
return getDocFormat() != null && getDocFormat() == FlexoDocFormat.LATEX;
}
/**
* @deprecated
* @param dontEscapeLatex
*/
@Deprecated
public void setDontEscapeLatex(boolean dontEscapeLatex) {
if (dontEscapeLatex) {
setDocFormat(FlexoDocFormat.LATEX);
}
setChanged();
notifyObservers(new DataModification("dontEscapeLatex", null, new Boolean(dontEscapeLatex)));
}
public FlexoDocFormat getDocFormat() {
return docFormat;
}
public void setDocFormat(FlexoDocFormat docFormat) {
setDocFormat(docFormat, true);
}
public void setDocFormat(FlexoDocFormat docFormat, boolean notify) {
FlexoDocFormat old = this.docFormat;
this.docFormat = docFormat;
if (notify) {
setChanged();
notifyObservers(new DataModification("docFormat", old, docFormat));
}
}
/**
* @return Returns the dontGenerate.
*/
public boolean getDontGenerate() {
return dontGenerate;
}
/**
* @param dontGenerate
* The dontGenerate to set.
*/
public void setDontGenerate(boolean dontGenerate) {
boolean old = this.dontGenerate;
if (old != dontGenerate) {
this.dontGenerate = dontGenerate;
setChanged();
notifyObservers(new WKFAttributeDataModification("dontGenerate", new Boolean(old), new Boolean(dontGenerate)));
}
}
public abstract String getClassNameKey();
public String getEnglishClassName() {
return FlexoLocalization.localizedForKeyAndLanguage(getClassNameKey(), Language.ENGLISH);
}
public String getFrenchClassName() {
return FlexoLocalization.localizedForKeyAndLanguage(getClassNameKey(), Language.FRENCH);
}
public String getDutchClassName() {
return FlexoLocalization.localizedForKeyAndLanguage(getClassNameKey(), Language.DUTCH);
}
private static final String EMPTY_STRING = "";
public boolean isDocEditable() {
return !isImported();
}
public String getDescription() {
if (description != null && description.startsWith("<html>First")) {
new Exception().printStackTrace();
}
return description;
}
public void setDescription(String description) {
if (!stringHasChanged(this.description, description)) {
return;
}
String old = this.description;
if (old == null && description == null) {
return;
}
if (old == null || !old.equals(description)) {
this.description = description;
setChanged();
notifyObservers(new DataModification("description", old, description));
}
}
public String getFullDescriptionWithOnlyBodyContent(String specificDescriptionType) {
StringBuilder sb = new StringBuilder();
if (getDescription() != null) {
String description = HTMLUtils.extractBodyContent(getDescription());
sb.append(description != null ? description : getDescription());
}
if (getHasSpecificDescriptions() && specificDescriptionType != null
&& getSpecificDescriptionForKey(specificDescriptionType) != null) {
String specifDesc = HTMLUtils.extractBodyContent(getSpecificDescriptionForKey(specificDescriptionType));
sb.append(specifDesc != null ? specifDesc : getSpecificDescriptionForKey(specificDescriptionType));
}
return sb.toString().trim();
}
public Map<String, String> getSpecificDescriptions() {
return specificDescriptions;
}
public void setSpecificDescriptions(Map<String, String> specificDescriptions) {
this.specificDescriptions = new TreeMap<String, String>(specificDescriptions);
}
public Vector<FlexoProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(Vector<FlexoProperty> customProperties) {
if (this.customProperties != null) {
for (FlexoProperty property : this.customProperties) {
property.setOwner(null);
}
}
this.customProperties = customProperties;
if (this.customProperties != null) {
for (FlexoProperty property : new Vector<FlexoProperty>(this.customProperties)) {
property.setOwner(this);
}
}
}
public void addToCustomProperties(FlexoProperty property) {
addToCustomProperties(property, false);
}
public void addToCustomProperties(FlexoProperty property, boolean insertSorted) {
if (insertSorted && property.getName() != null) {
int i = 0;
for (FlexoProperty p : customProperties) {
if (p.getName() != null && p.getName().compareTo(property.getName()) > 0) {
break;
}
i++;
}
customProperties.insertElementAt(property, i);
} else {
customProperties.add(property);
}
if (property != null) {
property.setOwner(this);
}
setChanged();
DataModification dm = new DataModification("customProperties", null, property);
notifyObservers(dm);
}
public void removeFromCustomProperties(FlexoProperty property) {
customProperties.remove(property);
}
public boolean hasPropertyNamed(String name) {
return getPropertyNamed(name) != null;
}
public FlexoProperty getPropertyNamed(String name) {
if (name == null) {
for (FlexoProperty p : getCustomProperties()) {
if (p.getName() == null) {
return p;
}
}
} else {
for (FlexoProperty p : getCustomProperties()) {
if (name.equals(p.getName())) {
return p;
}
}
}
return null;
}
public Vector<FlexoProperty> getProperties(String name) {
Vector<FlexoProperty> v = new Vector<FlexoProperty>();
if (name == null) {
for (FlexoProperty p : getCustomProperties()) {
if (p.getName() == null) {
v.add(p);
}
}
} else {
for (FlexoProperty p : getCustomProperties()) {
if (name.equals(p.getName())) {
v.add(p);
}
}
}
return v;
}
public void addProperty() {
if (addFlexoPropertyActionizer != null) {
addFlexoPropertyActionizer.run(this, null);
}
}
public boolean canSortProperties() {
return customProperties.size() > 1;
}
public void sortProperties() {
if (sortFlexoPropertiesActionizer != null) {
sortFlexoPropertiesActionizer.run(this, null);
}
}
public void deleteProperty(FlexoProperty property) {
if (deleteFlexoPropertyActionizer != null) {
deleteFlexoPropertyActionizer.run(property, null);
}
}
public boolean hasDescription() {
return getDescription() != null && getDescription().trim().length() > 0;
}
/**
* This property is used by the hightlightUncommentedItem mode. The decoration meaning that the description is missing will only appears
* on object for wich this method return true. So this method has to be overridden in subclass.
*
* @return
*/
public boolean isDescriptionImportant() {
return false;
}
public boolean hasSpecificHelp(String key) {
return getSpecificDescriptionForKey(key) != null && getSpecificDescriptionForKey(key).length() > 0;
}
public boolean hasSpecificDescriptionForKey(String key) {
return getSpecificDescriptionForKey(key) != null && getSpecificDescriptionForKey(key).trim().length() > 0;
}
public String getUserManualDescription() {
return getSpecificDescriptionForKey(DocType.DefaultDocType.UserManual.name());
}
public String getTechnicalDescription() {
return getSpecificDescriptionForKey(DocType.DefaultDocType.Technical.name());
}
public String getBusinessDescription() {
return getSpecificDescriptionForKey(DocType.DefaultDocType.Business.name());
}
/**
* @param businessDescription
*/
public void setBusinessDescription(String businessDescription) {
if (businessDescription != null) {
setSpecificDescriptionsForKey(businessDescription, DocType.DefaultDocType.Business.name());
} else {
removeSpecificDescriptionsWithKey(DocType.DefaultDocType.Business.name());
}
setChanged();
notifyObservers(new DataModification("businessDescription", null, businessDescription));
}
/**
* @param technicalDescription
*/
public void setTechnicalDescription(String technicalDescription) {
if (technicalDescription != null) {
setSpecificDescriptionsForKey(technicalDescription, DocType.DefaultDocType.Technical.name());
} else {
removeSpecificDescriptionsWithKey(DocType.DefaultDocType.Technical.name());
}
setChanged();
notifyObservers(new DataModification("technicalDescription", null, technicalDescription));
}
/**
* @param userManualDescription
*/
public void setUserManualDescription(String userManualDescription) {
if (userManualDescription != null) {
setSpecificDescriptionsForKey(userManualDescription, DocType.DefaultDocType.UserManual.name());
} else {
removeSpecificDescriptionsWithKey(DocType.DefaultDocType.UserManual.name());
}
setChanged();
notifyObservers(new DataModification("userManualDescription", null, userManualDescription));
}
public String getSpecificDescriptionForKey(String key) {
return specificDescriptions.get(key);
}
public void setSpecificDescriptionsForKey(String description, String key) {
specificDescriptions.put(key, description);
setChanged();
DataModification dm = new DataModification("specificDescriptions", null, description);
notifyObservers(dm);
}
public void removeSpecificDescriptionsWithKey(String key) {
specificDescriptions.remove(key);
}
@Override
public void setChanged() {
if (getProject() != null && !isDeserializing()) {
getProject().notifyObjectChanged(this);
}
super.setChanged();
}
private String expectedNotificationAttribute;
private boolean notificationHasBeenPerformed;
/**
* Override parent method by detecting unnotified setAttribute action Notify it if non-notified
*/
@Override
public void setObjectForKey(Object value, String key) {
notificationHasBeenPerformed = false;
expectedNotificationAttribute = key;
Object oldValue = objectForKey(key);
super.setObjectForKey(value, key);
if (!notificationHasBeenPerformed) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("SetAttribute for [" + key + "/" + getClass().getSimpleName() + "] (old value: " + oldValue
+ ", new value: " + value
+ ") was not notified. Please add setChanged()/notifyObservers(...) methods in required set method.");
}
setChanged();
notifyObservers(new AttributeDataModification(key, oldValue, value));
}
}
/**
*/
@Override
public void notifyObservers(DataModification dataModification) {
super.notifyObservers(dataModification);
if (expectedNotificationAttribute != null && dataModification != null
&& expectedNotificationAttribute.equals(dataModification.propertyName())) {
notificationHasBeenPerformed = true;
}
}
/**
*/
public void notifyObserversAsReentrantModification(DataModification dataModification) {
dataModification.setReentrant(true);
super.notifyObservers(dataModification);
if (expectedNotificationAttribute != null && expectedNotificationAttribute.equals(dataModification.propertyName())) {
notificationHasBeenPerformed = true;
}
}
public void addToReferencers(FlexoModelObjectReference<? extends FlexoModelObject> ref) {
if (referencers != null && !referencers.contains(ref)) {
referencers.add(ref);
}
}
public void removeFromReferencers(FlexoModelObjectReference<? extends FlexoModelObject> ref) {
if (referencers != null) {
referencers.remove(ref);
}
}
public Vector<FlexoModelObjectReference<?>> getReferencers() {
return referencers;
}
public static class FlexoDefaultComparator<E extends FlexoModelObject> implements Comparator<E> {
/**
* Overrides compare
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(E o1, E o2) {
if (o1.getFlexoID() > o2.getFlexoID()) {
return 1;
} else if (o1.getFlexoID() < o2.getFlexoID()) {
return -1;
} else {
return 0;
}
}
}
public static class FlexoNameComparator<E extends FlexoModelObject> implements Comparator<E> {
/**
* Overrides compare
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(E o1, E o2) {
if (o1.getName() == null) {
if (o2.getName() == null) {
return 0;
} else {
return -1;
}
} else if (o2.getName() == null) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
}
public final int compareTo(FlexoModelObject o2) {
if (getFlexoID() > o2.getFlexoID()) {
return 1;
} else if (getFlexoID() < o2.getFlexoID()) {
return -1;
} else {
return 0;
}
}
public final int compare(FlexoModelObject o1, FlexoModelObject o2) {
return o1.compareTo(o2);
}
// ============================================
// ============== Access to help ==============
// ============================================
private static HelpRetriever _helpRetriever = null;
public static interface HelpRetriever {
public String shortHelpForObject(FlexoModelObject object);
public String longHelpForObject(FlexoModelObject object);
}
/**
* Return help text for supplied object, as defined in DocResourceManager as long version Note: return an HTML version, with embedding
* <html>...</html> tags.
*/
public String getHelpText() {
if (_helpRetriever != null) {
return _helpRetriever.longHelpForObject(this);
}
return null;
}
/**
* Return help text for supplied object, as defined in DocResourceManager as short version Note: return an HTML version, with embedding
* <html>...</html> tags.
*/
public String getShortHelpText() {
if (_helpRetriever != null) {
return _helpRetriever.shortHelpForObject(this);
}
return null;
}
public static HelpRetriever getHelpRetriever() {
return _helpRetriever;
}
public static void setHelpRetriever(HelpRetriever retriever) {
_helpRetriever = retriever;
}
// ================================================
// ============== Dynamic properties ==============
// ================================================
private Hashtable<String, String> _dynamicProperties;
private Hashtable<String, String> _buildDynamicPropertiesWhenRequired() {
if (_dynamicProperties == null && !isSerializing()) {
// logger.info("Build _dynamicProperties for "+this);
_dynamicProperties = new Hashtable<String, String>();
}
return _dynamicProperties;
}
public Hashtable<String, String> getDynamicProperties() {
_buildDynamicPropertiesWhenRequired();
return _dynamicProperties;
}
public void setDynamicProperties(Hashtable<String, String> props) {
_dynamicProperties = props;
}
public void setDynamicPropertiesForKey(String value, String key) {
// logger.info("setDynamicPropertiesForKey: "+key+" value: "+value);
if (_dynamicProperties == null) {
_dynamicProperties = new Hashtable<String, String>();
}
_dynamicProperties.put(key, value);
}
public void removeDynamicPropertiesWithKey(String key) {
if (_dynamicProperties == null) {
_dynamicProperties = new Hashtable<String, String>();
}
_dynamicProperties.remove(key);
}
public boolean getHasSpecificDescriptions() {
return hasSpecificDescriptions;
}
public void setHasSpecificDescriptions(boolean hasSpecificDescription) {
if (this.hasSpecificDescriptions == hasSpecificDescription) {
return;
}
boolean old = this.hasSpecificDescriptions;
this.hasSpecificDescriptions = hasSpecificDescription;
setChanged();
notifyObservers(new DataModification("hasSpecificDescriptions", old, hasSpecificDescription));
}
/**
* Return a Vector of all embedded ModelObject
*
* @return a Vector of FlexoModelObject instances
*/
public Collection<FlexoModelObject> getEmbeddedObjects() {
return getXMLMapping().getEmbeddedObjectsForObject(this, FlexoModelObject.class);
}
/**
* Returns a vector of all objects that will be deleted if you call delete on this object.
*
* @return
*/
public Collection<FlexoModelObject> getAllRecursivelyEmbeddedDeletedObjects() {
return getXMLMapping().getEmbeddedObjectsForObject(this, FlexoModelObject.class, false, true);
}
public Collection<FlexoModelObject> getAllRecursivelyEmbeddedObjects() {
return getAllRecursivelyEmbeddedObjects(false);
}
public Collection<FlexoModelObject> getAllRecursivelyEmbeddedObjects(boolean maintainNaturalOrder) {
return getXMLMapping().getEmbeddedObjectsForObject(this, FlexoModelObject.class, maintainNaturalOrder, true);
}
/**
* Return a vector of all embedded objects on which the validation will be performed
*
* @return a Vector of Validable objects
*/
public Vector<Validable> getAllEmbeddedValidableObjects() {
Vector<Validable> vector = new Vector<Validable>();
for (FlexoModelObject o : getAllRecursivelyEmbeddedObjects()) {
if (o instanceof Validable) {
vector.add((Validable) o);
}
}
return vector;
}
public String getScreenshootName() {
ScreenshotResource screen = getProject().getScreenshotResource(this, false);
if (screen == null) {
return null;
}
return screen.getFileName();
}
@Override
public String toString() {
return getClass().getSimpleName() + "_" + (getName() != null ? getName() : getFlexoID());
}
protected <T> boolean requireChange(T oldValue, T newValue) {
return oldValue == null && newValue != null || oldValue != null && newValue == null || oldValue != null && newValue != null
&& !oldValue.equals(newValue);
}
public String getNextPropertyName() {
String base = FlexoLocalization.localizedForKey("property");
String attempt = base;
int i = 1;
while (getPropertyNamed(attempt) != null) {
attempt = base + "-" + i++;
}
return attempt;
}
private Vector<EditionPatternReference> _editionPatternReferences;
public Vector<EditionPatternReference> getEditionPatternReferences() {
return _editionPatternReferences;
}
public void setEditionPatternReferences(Vector<EditionPatternReference> editionPatternReferences) {
_editionPatternReferences = editionPatternReferences;
}
public boolean addToEditionPatternReferences(EditionPatternReference e) {
return _editionPatternReferences.add(e);
}
public boolean removeFromEditionPatternReferences(EditionPatternReference o) {
return _editionPatternReferences.remove(o);
}
public EditionPatternReference getEditionPatternReference(String editionPatternId, long instanceId) {
if (editionPatternId == null) {
return null;
}
if (_editionPatternReferences == null) {
return null;
}
for (EditionPatternReference r : _editionPatternReferences) {
if (r.getEditionPattern().getName().equals(editionPatternId) && r.getInstanceId() == instanceId) {
return r;
}
}
return null;
}
public EditionPatternReference getEditionPatternReference(EditionPatternInstance epInstance) {
if (_editionPatternReferences == null) {
logger.warning("Unexpected _editionPatternReferences=null !!!");
return null;
}
for (EditionPatternReference r : _editionPatternReferences) {
if (r.getEditionPatternInstance() == epInstance) {
return r;
}
}
return null;
}
// Return first one if many
public EditionPatternReference getEditionPatternReference(String editionPatternId) {
if (editionPatternId == null) {
return null;
}
for (EditionPatternReference r : _editionPatternReferences) {
if (r.getEditionPattern().getName().equals(editionPatternId)) {
return r;
}
}
return null;
}
// Return first one if many
public EditionPatternReference getEditionPatternReference(EditionPattern editionPattern) {
if (editionPattern == null) {
return null;
}
for (EditionPatternReference r : _editionPatternReferences) {
// System.out.println("1: " + r.getEditionPattern().getName() + " 2: " + editionPattern.getName());
if (r.getEditionPattern().getName().equals(editionPattern.getName())) {
return r;
}
}
return null;
}
public void registerEditionPatternReference(EditionPatternInstance editionPatternInstance, PatternRole patternRole) {
EditionPatternReference existingReference = getEditionPatternReference(editionPatternInstance);
if (existingReference == null) {
// logger.info("registerEditionPatternReference for " + editionPatternInstance.debug());
EditionPatternReference newReference = new EditionPatternReference(editionPatternInstance, patternRole);
addToEditionPatternReferences(newReference);
setChanged();
} else {
if (existingReference.getPatternRole() != patternRole) {
logger.warning("Called for register a new EditionPatternReference with an already existing EditionPatternReference with a different PatternRole");
}
}
}
public void unregisterEditionPatternReference(EditionPatternInstance editionPatternInstance, PatternRole patternRole) {
EditionPatternReference referenceToRemove = getEditionPatternReference(editionPatternInstance);
if (referenceToRemove == null) {
logger.warning("Called for unregister EditionPatternReference for unexisting reference to edition pattern instance EP="
+ editionPatternInstance.getPattern().getName() + " id=" + editionPatternInstance.getInstanceId());
for (EditionPatternReference ref : getEditionPatternReferences()) {
logger.warning("* Reference:");
logger.warning(ref.debug());
}
} else {
removeFromEditionPatternReferences(referenceToRemove);
setChanged();
}
}
@Deprecated
public Vector<TabModel> inspectionExtraTabs() {
return null;
}
/*
* private Vector<TabModel> _tabList;
*
* public Vector<TabModel> inspectionExtraTabs() { if (_tabList == null) { _tabList = new Vector<TabModel>(); if
* (getEditionPatternReferences() != null) { for (EditionPatternReference ref : getEditionPatternReferences()) { EditionPatternInspector
* inspector = ref.getEditionPattern().getInspector(); if (inspector != null) { //for (Integer i : inspector.getTabs().keySet()) { //
* _tabList.add(inspector.getTabs().get(i)); //} } } } } return _tabList; }
*/
public String getInspectorTitle() {
// By default, take default inspector name
return null;
}
public String makeReference() {
return FlexoModelObjectReference.getSerializationRepresentationForObject(this, true);
}
/**
* Return true is this object is somewhere involved as a primary representation pattern role in any of its EditionPatternReferences
*
* @return
*/
public boolean providesSupportAsPrimaryRole() {
if (getEditionPatternReferences() != null) {
if (getEditionPatternReferences().size() > 0) {
for (EditionPatternReference r : getEditionPatternReferences()) {
if (r.getPatternRole() == null) {
logger.warning("Found an EditionPatternReference with a null pattern role. Please investigate...");
} else if (r.getPatternRole().getIsPrimaryRole()) {
return true;
}
}
}
}
return false;
}
}
| true | true | public void delete() {
// if (logger.isLoggable(Level.FINE)) logger.fine ("Delete
// "+this.getClass().getName()+" : "+this);
if (isDeleted) {
// in some case : the delete may be called twice on a sequence (in case of deletion of last widget of the sequence)...
// and it will fail
// a good idea would be to avoid this double invocation.
// In the mean time, this little hack will do the trick.
return;
}
isDeleted = true;
if (getProject() != null) {
if (isRegistered) {
getProject().unregister(this);
}
isRegistered = false;
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Project is null for " + this);
}
}
for (EditionPatternReference ref : new ArrayList<EditionPatternReference>(getEditionPatternReferences())) {
if (ref.getEditionPatternInstance() != null) {
ref.getEditionPatternInstance().nullifyPatternActor(ref.getPatternRole());
}
ref.delete();
}
_editionPatternReferences.clear();
_editionPatternReferences = null;
for (FlexoModelObjectReference ref : new ArrayList<FlexoModelObjectReference>(referencers)) {
ref.notifyObjectDeletion();
}
referencers.clear();
referencers = null;
setChanged();
notifyObservers(new ObjectDeleted(this));
if (getProject() != null) {
getProject().notifyObjectDeleted(this);
}
}
| public void delete() {
// if (logger.isLoggable(Level.FINE)) logger.fine ("Delete
// "+this.getClass().getName()+" : "+this);
if (isDeleted) {
// in some case : the delete may be called twice on a sequence (in case of deletion of last widget of the sequence)...
// and it will fail
// a good idea would be to avoid this double invocation.
// In the mean time, this little hack will do the trick.
return;
}
isDeleted = true;
if (getProject() != null) {
if (isRegistered) {
getProject().unregister(this);
}
isRegistered = false;
} else {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Project is null for " + this.getClass().getSimpleName() + "_" + this.getFlexoID());
}
}
for (EditionPatternReference ref : new ArrayList<EditionPatternReference>(getEditionPatternReferences())) {
if (ref.getEditionPatternInstance() != null) {
ref.getEditionPatternInstance().nullifyPatternActor(ref.getPatternRole());
}
ref.delete();
}
_editionPatternReferences.clear();
_editionPatternReferences = null;
for (FlexoModelObjectReference ref : new ArrayList<FlexoModelObjectReference>(referencers)) {
ref.notifyObjectDeletion();
}
referencers.clear();
referencers = null;
setChanged();
notifyObservers(new ObjectDeleted(this));
if (getProject() != null) {
getProject().notifyObjectDeleted(this);
}
}
|
diff --git a/pdfbox/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java b/pdfbox/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java
index 21a4de980..26998c15f 100644
--- a/pdfbox/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java
+++ b/pdfbox/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java
@@ -1,295 +1,295 @@
/*
* 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.pdfbox.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
/**
* Test suite for PDFTextStripper.
*
* FILE SET VALIDATION
*
* This test suite is designed to test PDFToImage using a set of PDF
* files and known good output for each. The default mode of testAll()
* is to process each *.pdf file in "src/test/resources/input/rendering". An output file is
* created in "target/test-output/rendering" with the same name as the PDF file, plus an
* additional page number and ".png" suffix.
*
* The output file is then tested against a known good result file from
* the input directory (again, with the same name as the tested PDF file,
* but with the additional page number and ".png" suffix).
*
* Currently, testing against known output is simply a byte-for-byte comparison
*
*In the future, testing against the known output may be accomplished using PerceptualDiff
* http://sourceforge.net/projects/pdiff
*
*
* @author <a href="mailto:[email protected]">Daniel Wilson</a>
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.1 $
*/
public class TestPDFToImage extends TestCase
{
/**
* Logger instance.
*/
private static final Log log = LogFactory.getLog(TestPDFToImage.class);
private boolean bFail = false;
private PDFRenderer renderer = null;
private File mcurFile = null;
/**
* Test class constructor.
*
* @param name The name of the test class.
*
* @throws IOException If there is an error creating the test.
*/
public TestPDFToImage( String name ) throws IOException
{
super( name );
}
/**
* Test suite setup.
*/
public void setUp()
{
// If you want to test a single file using DEBUG logging, from an IDE,
// you can do something like this:
//
// System.setProperty("org.apache.pdfbox.util.TextStripper.file", "FVS318Ref.pdf");
}
/**
* Validate text extraction on a single file.
*
* @param file The file to validate
* @param bLogResult Whether to log the extracted text
* @param inDir Name of the input directory
* @param outDir Name of the output directory
* @throws Exception when there is an exception
*/
public void doTestFile(File file, boolean bLogResult, String inDir, String outDir)
throws Exception
{
PDDocument document = null;
log.info("Preparing to convert " + file.getName());
try
{
document = PDDocument.load(file);
renderer = new PDFRenderer(document);
String outputPrefix = outDir + file.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
- BufferedImage image = renderer.renderImage(i);
+ BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
String fileName = outputPrefix + (i + 1);
log.info("Writing: " + fileName + ".pbg");
ImageIO.write(image, "PNG", new File(fileName));
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error converting file " + file.getName(), e);
}
finally
{
document.close();
}
//Now check the resulting files ... did we get identical PNG(s)?
try
{
mcurFile = file;
File[] outFiles = new File(outDir).listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".png") && name.startsWith(mcurFile.getName(),0));
}
});
for (int n = 0; n < outFiles.length; n++)
{
File inFile = new File(inDir + '/' + outFiles[n].getName());
if (!inFile.exists() ||
!filesAreIdentical(outFiles[n], inFile))
{
this.bFail=true;
log.warn("*** TEST FAILURE *** Input and output not identical for file: " + inFile.getName());
}
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error comparing file output for " + file.getName(), e);
}
}
/**
* Test to validate image rendering of file set.
*
* @throws Exception when there is an exception
*/
public void testRenderImage()
throws Exception
{
String filename = System.getProperty("org.apache.pdfbox.util.TextStripper.file");
String inDir = "src/test/resources/input/rendering";
String outDir = "target/test-output/rendering/";
String inDirExt = "target/test-input-ext/rendering";
String outDirExt = "target/test-output-ext/rendering";
if ((filename == null) || (filename.length() == 0))
{
File[] testFiles = new File(inDir).listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".pdf") || name.endsWith(".ai"));
}
});
for (int n = 0; n < testFiles.length; n++)
{
doTestFile(testFiles[n], false, inDir, outDir);
}
testFiles = new File(inDirExt).listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".pdf") || name.endsWith(".ai"));
}
});
if (testFiles != null)
{
for (int n = 0; n < testFiles.length; n++)
{
doTestFile(testFiles[n], false, inDirExt, outDirExt);
}
}
}
else
{
doTestFile(new File(inDir, filename), true, inDir, outDir);
}
if (this.bFail)
{
fail("One or more failures, see test log for details");
}
}
/**
* Set the tests in the suite for this test class.
*
* @return the Suite.
*/
public static Test suite()
{
return new TestSuite( TestPDFToImage.class );
}
/**
* Command line execution.
*
* @param args Command line arguments.
*/
public static void main( String[] args )
{
String[] arg = {TestPDFToImage.class.getName() };
junit.textui.TestRunner.main( arg );
}
private boolean filesAreIdentical(File left, File right) throws IOException
{
//http://forum.java.sun.com/thread.jspa?threadID=688105&messageID=4003259
/* -- I reworked ASSERT's into IF statement -- dwilson
assert left != null;
assert right != null;
assert left.exists();
assert right.exists();
*/
if(left != null && right != null && left.exists() && right.exists())
{
if (left.length() != right.length())
{
return false;
}
FileInputStream lin = new FileInputStream(left);
FileInputStream rin = new FileInputStream(right);
try
{
byte[] lbuffer = new byte[4096];
byte[] rbuffer = new byte[lbuffer.length];
for (int lcount = 0; (lcount = lin.read(lbuffer)) > 0;)
{
int bytesRead = 0;
for (int rcount = 0; (rcount = rin.read(rbuffer, bytesRead, lcount - bytesRead)) > 0;)
{
bytesRead += rcount;
}
for (int byteIndex = 0; byteIndex < lcount; byteIndex++)
{
if (lbuffer[byteIndex] != rbuffer[byteIndex])
{
return false;
}
}
}
}
finally
{
lin.close();
rin.close();
}
return true;
}
else
{
return false;
}
}
}
| true | true | public void doTestFile(File file, boolean bLogResult, String inDir, String outDir)
throws Exception
{
PDDocument document = null;
log.info("Preparing to convert " + file.getName());
try
{
document = PDDocument.load(file);
renderer = new PDFRenderer(document);
String outputPrefix = outDir + file.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
BufferedImage image = renderer.renderImage(i);
String fileName = outputPrefix + (i + 1);
log.info("Writing: " + fileName + ".pbg");
ImageIO.write(image, "PNG", new File(fileName));
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error converting file " + file.getName(), e);
}
finally
{
document.close();
}
//Now check the resulting files ... did we get identical PNG(s)?
try
{
mcurFile = file;
File[] outFiles = new File(outDir).listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".png") && name.startsWith(mcurFile.getName(),0));
}
});
for (int n = 0; n < outFiles.length; n++)
{
File inFile = new File(inDir + '/' + outFiles[n].getName());
if (!inFile.exists() ||
!filesAreIdentical(outFiles[n], inFile))
{
this.bFail=true;
log.warn("*** TEST FAILURE *** Input and output not identical for file: " + inFile.getName());
}
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error comparing file output for " + file.getName(), e);
}
}
| public void doTestFile(File file, boolean bLogResult, String inDir, String outDir)
throws Exception
{
PDDocument document = null;
log.info("Preparing to convert " + file.getName());
try
{
document = PDDocument.load(file);
renderer = new PDFRenderer(document);
String outputPrefix = outDir + file.getName() + "-";
int numPages = document.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(document);
for (int i = 0; i < numPages; i++)
{
BufferedImage image = renderer.renderImageWithDPI(i, 96); // Windows native DPI
String fileName = outputPrefix + (i + 1);
log.info("Writing: " + fileName + ".pbg");
ImageIO.write(image, "PNG", new File(fileName));
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error converting file " + file.getName(), e);
}
finally
{
document.close();
}
//Now check the resulting files ... did we get identical PNG(s)?
try
{
mcurFile = file;
File[] outFiles = new File(outDir).listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return (name.endsWith(".png") && name.startsWith(mcurFile.getName(),0));
}
});
for (int n = 0; n < outFiles.length; n++)
{
File inFile = new File(inDir + '/' + outFiles[n].getName());
if (!inFile.exists() ||
!filesAreIdentical(outFiles[n], inFile))
{
this.bFail=true;
log.warn("*** TEST FAILURE *** Input and output not identical for file: " + inFile.getName());
}
}
}
catch(Exception e)
{
this.bFail=true;
log.error("Error comparing file output for " + file.getName(), e);
}
}
|
diff --git a/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java b/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
index 10d0db01..75dddf77 100644
--- a/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
+++ b/test/web/org/openmrs/web/patient/PatientDashboardGraphControllerTest.java
@@ -1,61 +1,61 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.patient;
import junit.framework.Assert;
import org.junit.Test;
import org.openmrs.test.Verifies;
import org.openmrs.web.controller.patient.PatientDashboardGraphController;
import org.openmrs.web.controller.patient.PatientGraphData;
import org.openmrs.web.test.BaseWebContextSensitiveTest;
import org.springframework.ui.ModelMap;
/**
* Test for graphs on the patient dashboard
*/
public class PatientDashboardGraphControllerTest extends BaseWebContextSensitiveTest {
/**
* Test getting a concept by name and by partial name.
*
* @see {@link PatientDashboardGraphController#showGraphData(Integer, Integer, ModelMap)}
*/
@Test
@Verifies(value = "return json data with observation details and critical values for the concept", method = "showGraphData(Integer, Integer, ModelMap)")
public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
- Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139509800000,2.0],[1139423400000,1.0]]}", graph
+ Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139547600000,2.0],[1139461200000,1.0]]}", graph
.toString());
}
/**
* Test the path of the form for rendering the json data
*
* @see {@link PatientDashboardGraphController#showGraphData(Integer, Integer, ModelMap)}
*/
@Test
@Verifies(value = "return form for rendering the json data", method = "showGraphData(Integer, Integer, ModelMap)")
public void shouldDisplayPatientDashboardGraphForm() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
Assert.assertEquals("patientGraphJsonForm", new PatientDashboardGraphController().showGraphData(2, 1,
new ModelMap()));
}
}
| true | true | public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139509800000,2.0],[1139423400000,1.0]]}", graph
.toString());
}
| public void shouldReturnJSONWithPatientObservationDetails() throws Exception {
executeDataSet("org/openmrs/api/include/ObsServiceTest-initial.xml");
PatientDashboardGraphController controller = new PatientDashboardGraphController();
ModelMap map = new ModelMap();
controller.showGraphData(2, 1, map);
PatientGraphData graph = (PatientGraphData) map.get("graph");
Assert.assertEquals("{\"absolute\":{\"high\":50.0,\"low\":2.0},\"critical\":{\"high\":null,\"low\":null},\"normal\":{\"high\":null,\"low\":null},\"data\":[[1139547600000,2.0],[1139461200000,1.0]]}", graph
.toString());
}
|
diff --git a/src/main/java/in/com/tw/jellybean/DataStore.java b/src/main/java/in/com/tw/jellybean/DataStore.java
index cdd9ec7..8f5a355 100644
--- a/src/main/java/in/com/tw/jellybean/DataStore.java
+++ b/src/main/java/in/com/tw/jellybean/DataStore.java
@@ -1,28 +1,28 @@
package in.com.tw.jellybean;
import in.com.tw.jellybean.models.Consultant;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: somisetn
* Date: 31/07/13
* Time: 3:22 PM
* To change this template use File | Settings | File Templates.
*/
public class DataStore {
public List<Consultant> getConsultants() {
return consultants;
}
List<Consultant> consultants = new ArrayList<Consultant>();
public boolean saveConsultant(Consultant consultant) {
consultants.add(consultant);
- return false;
+ return true;
}
}
| true | true | public boolean saveConsultant(Consultant consultant) {
consultants.add(consultant);
return false;
}
| public boolean saveConsultant(Consultant consultant) {
consultants.add(consultant);
return true;
}
|
diff --git a/src/friskstick/cops/plugin/FriskCommand.java b/src/friskstick/cops/plugin/FriskCommand.java
index f58f4cc..f7cfc46 100644
--- a/src/friskstick/cops/plugin/FriskCommand.java
+++ b/src/friskstick/cops/plugin/FriskCommand.java
@@ -1,148 +1,148 @@
package friskstick.cops.plugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
/*
*
* This is where the command for frisk will be implemented, making it easier to organize the program.
*
*/
public class FriskCommand implements CommandExecutor{
private FriskStick plugin;
JailPlayer jailed = new JailPlayer();
public FriskCommand(FriskStick plugin) {
this.plugin = plugin;
}
int index = 0;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
- player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
- player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
|
diff --git a/src/com/android/bluetooth/btservice/RemoteDevices.java b/src/com/android/bluetooth/btservice/RemoteDevices.java
index 04bc1c2..a60f977 100755
--- a/src/com/android/bluetooth/btservice/RemoteDevices.java
+++ b/src/com/android/bluetooth/btservice/RemoteDevices.java
@@ -1,464 +1,465 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.bluetooth.btservice;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.util.Log;
import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
final class RemoteDevices {
private static final boolean DBG = false;
private static final String TAG = "BluetoothRemoteDevices";
private static BluetoothAdapter mAdapter;
private static AdapterService mAdapterService;
private static ArrayList<BluetoothDevice> mSdpTracker;
private Object mObject = new Object();
private static final int UUID_INTENT_DELAY = 6000;
private static final int MESSAGE_UUID_INTENT = 1;
private HashMap<BluetoothDevice, DeviceProperties> mDevices;
RemoteDevices(AdapterService service) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapterService = service;
mSdpTracker = new ArrayList<BluetoothDevice>();
mDevices = new HashMap<BluetoothDevice, DeviceProperties>();
}
void cleanup() {
if (mSdpTracker !=null)
mSdpTracker.clear();
if (mDevices != null)
mDevices.clear();
}
public Object Clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
DeviceProperties getDeviceProperties(BluetoothDevice device) {
synchronized (mDevices) {
return mDevices.get(device);
}
}
BluetoothDevice getDevice(byte[] address) {
for (BluetoothDevice dev : mDevices.keySet()) {
if (dev.getAddress().equals(Utils.getAddressStringFromByte(address))) {
return dev;
}
}
return null;
}
DeviceProperties addDeviceProperties(byte[] address) {
synchronized (mDevices) {
DeviceProperties prop = new DeviceProperties();
BluetoothDevice device =
mAdapter.getRemoteDevice(Utils.getAddressStringFromByte(address));
prop.mAddress = address;
mDevices.put(device, prop);
return prop;
}
}
class DeviceProperties {
private String mName;
private byte[] mAddress;
private int mBluetoothClass;
private short mRssi;
private ParcelUuid[] mUuids;
private int mDeviceType;
private String mAlias;
private int mBondState;
DeviceProperties() {
mBondState = BluetoothDevice.BOND_NONE;
}
/**
* @return the mName
*/
String getName() {
synchronized (mObject) {
return mName;
}
}
/**
* @return the mClass
*/
int getBluetoothClass() {
synchronized (mObject) {
return mBluetoothClass;
}
}
/**
* @return the mUuids
*/
ParcelUuid[] getUuids() {
synchronized (mObject) {
return mUuids;
}
}
/**
* @return the mAddress
*/
byte[] getAddress() {
synchronized (mObject) {
return mAddress;
}
}
/**
* @return mRssi
*/
short getRssi() {
synchronized (mObject) {
return mRssi;
}
}
/**
* @return mDeviceType
*/
int getDeviceType() {
synchronized (mObject) {
return mDeviceType;
}
}
/**
* @return the mAlias
*/
String getAlias() {
synchronized (mObject) {
return mAlias;
}
}
/**
* @param mAlias the mAlias to set
*/
void setAlias(String mAlias) {
synchronized (mObject) {
mAdapterService.setDevicePropertyNative(mAddress,
AbstractionLayer.BT_PROPERTY_REMOTE_FRIENDLY_NAME, mAlias.getBytes());
}
}
/**
* @param mBondState the mBondState to set
*/
void setBondState(int mBondState) {
synchronized (mObject) {
this.mBondState = mBondState;
if (mBondState == BluetoothDevice.BOND_NONE)
{
/* Clearing the Uuids local copy when the device is unpaired. If not cleared,
cachedBluetoothDevice issued a connect using the local cached copy of uuids,
without waiting for the ACTION_UUID intent.
This was resulting in multiple calls to connect().*/
mUuids = null;
}
}
}
/**
* @return the mBondState
*/
int getBondState() {
synchronized (mObject) {
return mBondState;
}
}
}
private void sendUuidIntent(BluetoothDevice device) {
DeviceProperties prop = getDeviceProperties(device);
Intent intent = new Intent(BluetoothDevice.ACTION_UUID);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothDevice.EXTRA_UUID, prop == null? null: prop.mUuids);
mAdapterService.sendBroadcast(intent, AdapterService.BLUETOOTH_ADMIN_PERM);
//Remove the outstanding UUID request
mSdpTracker.remove(device);
}
private void sendDisplayPinIntent(byte[] address, int pin) {
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, getDevice(address));
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, pin);
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_ADMIN_PERM);
}
void devicePropertyChangedCallback(byte[] address, int[] types, byte[][] values) {
Intent intent;
byte[] val;
int type;
BluetoothDevice bdDevice = getDevice(address);
DeviceProperties device;
if (bdDevice == null) {
device = addDeviceProperties(address);
bdDevice = getDevice(address);
} else {
device = getDeviceProperties(bdDevice);
}
for (int j = 0; j < types.length; j++) {
type = types[j];
val = values[j];
if(val.length <= 0)
errorLog("devicePropertyChangedCallback: bdDevice: " + bdDevice + ", value is empty for type: " + type);
else {
synchronized(mObject) {
switch (type) {
case AbstractionLayer.BT_PROPERTY_BDNAME:
device.mName = new String(val);
intent = new Intent(BluetoothDevice.ACTION_NAME_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_NAME, device.mName);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote Device name is: " + device.mName);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_FRIENDLY_NAME:
if (device.mAlias != null) {
System.arraycopy(val, 0, device.mAlias, 0, val.length);
}
else {
device.mAlias = new String(val);
}
break;
case AbstractionLayer.BT_PROPERTY_BDADDR:
device.mAddress = val;
debugLog("Remote Address is:" + Utils.getAddressStringFromByte(val));
break;
case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE:
device.mBluetoothClass = Utils.byteArrayToInt(val);
intent = new Intent(BluetoothDevice.ACTION_CLASS_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_CLASS,
new BluetoothClass(device.mBluetoothClass));
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote class is:" + device.mBluetoothClass);
break;
case AbstractionLayer.BT_PROPERTY_UUIDS:
int numUuids = val.length/AbstractionLayer.BT_UUID_SIZE;
device.mUuids = Utils.byteArrayToUuid(val);
sendUuidIntent(bdDevice);
break;
case AbstractionLayer.BT_PROPERTY_TYPE_OF_DEVICE:
// The device type from hal layer, defined in bluetooth.h,
// matches the type defined in BluetoothDevice.java
device.mDeviceType = Utils.byteArrayToInt(val);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_RSSI:
- device.mRssi = Utils.byteArrayToShort(val);
+ // RSSI from hal is in one byte
+ device.mRssi = val[0];
break;
}
}
}
}
}
void deviceFoundCallback(byte[] address) {
// The device properties are already registered - we can send the intent
// now
BluetoothDevice device = getDevice(address);
debugLog("deviceFoundCallback: Remote Address is:" + device);
DeviceProperties deviceProp = getDeviceProperties(device);
if (deviceProp == null) {
errorLog("Device Properties is null for Device:" + device);
return;
}
Intent intent = new Intent(BluetoothDevice.ACTION_FOUND);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.putExtra(BluetoothDevice.EXTRA_CLASS,
new BluetoothClass(Integer.valueOf(deviceProp.mBluetoothClass)));
intent.putExtra(BluetoothDevice.EXTRA_RSSI, deviceProp.mRssi);
intent.putExtra(BluetoothDevice.EXTRA_NAME, deviceProp.mName);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
}
void pinRequestCallback(byte[] address, byte[] name, int cod) {
//TODO(BT): Get wakelock and update name and cod
BluetoothDevice bdDevice = getDevice(address);
if (bdDevice == null) {
addDeviceProperties(address);
}
BluetoothClass btClass = bdDevice.getBluetoothClass();
int btDeviceClass = btClass.getDeviceClass();
if (btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD ||
btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD_POINTING) {
// Its a keyboard. Follow the HID spec recommendation of creating the
// passkey and displaying it to the user. If the keyboard doesn't follow
// the spec recommendation, check if the keyboard has a fixed PIN zero
// and pair.
//TODO: Add sFixedPinZerosAutoPairKeyboard() and maintain list of devices that have fixed pin
/*if (mAdapterService.isFixedPinZerosAutoPairKeyboard(address)) {
mAdapterService.setPin(address, BluetoothDevice.convertPinToBytes("0000"));
return;
}*/
// Generate a variable PIN. This is not truly random but good enough.
int pin = (int) Math.floor(Math.random() * 1000000);
sendDisplayPinIntent(address, pin);
return;
}
infoLog("pinRequestCallback: " + address + " name:" + name + " cod:" +
cod);
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, getDevice(address));
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.PAIRING_VARIANT_PIN);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_ADMIN_PERM);
return;
}
void sspRequestCallback(byte[] address, byte[] name, int cod, int pairingVariant,
int passkey) {
//TODO(BT): Get wakelock and update name and cod
BluetoothDevice bdDevice = getDevice(address);
if (bdDevice == null) {
addDeviceProperties(address);
}
infoLog("sspRequestCallback: " + address + " name: " + name + " cod: " +
cod + " pairingVariant " + pairingVariant + " passkey: " + passkey);
int variant;
boolean displayPasskey = false;
if (pairingVariant == AbstractionLayer.BT_SSP_VARIANT_PASSKEY_CONFIRMATION) {
variant = BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION;
displayPasskey = true;
} else if (pairingVariant == AbstractionLayer.BT_SSP_VARIANT_CONSENT) {
variant = BluetoothDevice.PAIRING_VARIANT_CONSENT;
} else if (pairingVariant == AbstractionLayer.BT_SSP_VARIANT_PASSKEY_ENTRY) {
variant = BluetoothDevice.PAIRING_VARIANT_PASSKEY;
} else if (pairingVariant == AbstractionLayer.BT_SSP_VARIANT_PASSKEY_NOTIFICATION) {
variant = BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY;
displayPasskey = true;
} else {
errorLog("SSP Pairing variant not present");
return;
}
BluetoothDevice device = getDevice(address);
if (device == null) {
warnLog("Device is not known for:" + Utils.getAddressStringFromByte(address));
addDeviceProperties(address);
device = getDevice(address);
}
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
if (displayPasskey) {
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, passkey);
}
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, variant);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_ADMIN_PERM);
}
void aclStateChangeCallback(int status, byte[] address, int newState) {
BluetoothDevice device = getDevice(address);
if (device == null) {
errorLog("aclStateChangeCallback: Device is NULL");
return;
}
Intent intent = null;
if (newState == AbstractionLayer.BT_ACL_STATE_CONNECTED) {
intent = new Intent(BluetoothDevice.ACTION_ACL_CONNECTED);
debugLog("aclStateChangeCallback: State:Connected to Device:" + device);
} else {
intent = new Intent(BluetoothDevice.ACTION_ACL_DISCONNECTED);
debugLog("aclStateChangeCallback: State:DisConnected to Device:" + device);
}
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
}
void fetchUuids(BluetoothDevice device) {
if (mSdpTracker.contains(device)) return;
mSdpTracker.add(device);
Message message = mHandler.obtainMessage(MESSAGE_UUID_INTENT);
message.obj = device;
mHandler.sendMessageDelayed(message, UUID_INTENT_DELAY);
//mAdapterService.getDevicePropertyNative(Utils.getBytesFromAddress(device.getAddress()), AbstractionLayer.BT_PROPERTY_UUIDS);
mAdapterService.getRemoteServicesNative(Utils.getBytesFromAddress(device.getAddress()));
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_UUID_INTENT:
BluetoothDevice device = (BluetoothDevice)msg.obj;
if (device != null) {
sendUuidIntent(device);
}
break;
}
}
};
private void errorLog(String msg) {
Log.e(TAG, msg);
}
private void debugLog(String msg) {
if (DBG) Log.d(TAG, msg);
}
private void infoLog(String msg) {
if (DBG) Log.i(TAG, msg);
}
private void warnLog(String msg) {
Log.w(TAG, msg);
}
}
| true | true | void devicePropertyChangedCallback(byte[] address, int[] types, byte[][] values) {
Intent intent;
byte[] val;
int type;
BluetoothDevice bdDevice = getDevice(address);
DeviceProperties device;
if (bdDevice == null) {
device = addDeviceProperties(address);
bdDevice = getDevice(address);
} else {
device = getDeviceProperties(bdDevice);
}
for (int j = 0; j < types.length; j++) {
type = types[j];
val = values[j];
if(val.length <= 0)
errorLog("devicePropertyChangedCallback: bdDevice: " + bdDevice + ", value is empty for type: " + type);
else {
synchronized(mObject) {
switch (type) {
case AbstractionLayer.BT_PROPERTY_BDNAME:
device.mName = new String(val);
intent = new Intent(BluetoothDevice.ACTION_NAME_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_NAME, device.mName);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote Device name is: " + device.mName);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_FRIENDLY_NAME:
if (device.mAlias != null) {
System.arraycopy(val, 0, device.mAlias, 0, val.length);
}
else {
device.mAlias = new String(val);
}
break;
case AbstractionLayer.BT_PROPERTY_BDADDR:
device.mAddress = val;
debugLog("Remote Address is:" + Utils.getAddressStringFromByte(val));
break;
case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE:
device.mBluetoothClass = Utils.byteArrayToInt(val);
intent = new Intent(BluetoothDevice.ACTION_CLASS_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_CLASS,
new BluetoothClass(device.mBluetoothClass));
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote class is:" + device.mBluetoothClass);
break;
case AbstractionLayer.BT_PROPERTY_UUIDS:
int numUuids = val.length/AbstractionLayer.BT_UUID_SIZE;
device.mUuids = Utils.byteArrayToUuid(val);
sendUuidIntent(bdDevice);
break;
case AbstractionLayer.BT_PROPERTY_TYPE_OF_DEVICE:
// The device type from hal layer, defined in bluetooth.h,
// matches the type defined in BluetoothDevice.java
device.mDeviceType = Utils.byteArrayToInt(val);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_RSSI:
device.mRssi = Utils.byteArrayToShort(val);
break;
}
}
}
}
}
| void devicePropertyChangedCallback(byte[] address, int[] types, byte[][] values) {
Intent intent;
byte[] val;
int type;
BluetoothDevice bdDevice = getDevice(address);
DeviceProperties device;
if (bdDevice == null) {
device = addDeviceProperties(address);
bdDevice = getDevice(address);
} else {
device = getDeviceProperties(bdDevice);
}
for (int j = 0; j < types.length; j++) {
type = types[j];
val = values[j];
if(val.length <= 0)
errorLog("devicePropertyChangedCallback: bdDevice: " + bdDevice + ", value is empty for type: " + type);
else {
synchronized(mObject) {
switch (type) {
case AbstractionLayer.BT_PROPERTY_BDNAME:
device.mName = new String(val);
intent = new Intent(BluetoothDevice.ACTION_NAME_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_NAME, device.mName);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote Device name is: " + device.mName);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_FRIENDLY_NAME:
if (device.mAlias != null) {
System.arraycopy(val, 0, device.mAlias, 0, val.length);
}
else {
device.mAlias = new String(val);
}
break;
case AbstractionLayer.BT_PROPERTY_BDADDR:
device.mAddress = val;
debugLog("Remote Address is:" + Utils.getAddressStringFromByte(val));
break;
case AbstractionLayer.BT_PROPERTY_CLASS_OF_DEVICE:
device.mBluetoothClass = Utils.byteArrayToInt(val);
intent = new Intent(BluetoothDevice.ACTION_CLASS_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
intent.putExtra(BluetoothDevice.EXTRA_CLASS,
new BluetoothClass(device.mBluetoothClass));
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mAdapterService.sendBroadcast(intent, mAdapterService.BLUETOOTH_PERM);
debugLog("Remote class is:" + device.mBluetoothClass);
break;
case AbstractionLayer.BT_PROPERTY_UUIDS:
int numUuids = val.length/AbstractionLayer.BT_UUID_SIZE;
device.mUuids = Utils.byteArrayToUuid(val);
sendUuidIntent(bdDevice);
break;
case AbstractionLayer.BT_PROPERTY_TYPE_OF_DEVICE:
// The device type from hal layer, defined in bluetooth.h,
// matches the type defined in BluetoothDevice.java
device.mDeviceType = Utils.byteArrayToInt(val);
break;
case AbstractionLayer.BT_PROPERTY_REMOTE_RSSI:
// RSSI from hal is in one byte
device.mRssi = val[0];
break;
}
}
}
}
}
|
diff --git a/agit/src/main/java/com/madgag/agit/diff/DiffSliderView.java b/agit/src/main/java/com/madgag/agit/diff/DiffSliderView.java
index c83f087..382a18b 100644
--- a/agit/src/main/java/com/madgag/agit/diff/DiffSliderView.java
+++ b/agit/src/main/java/com/madgag/agit/diff/DiffSliderView.java
@@ -1,115 +1,115 @@
/*
* Copyright (c) 2011 Roberto Tyley
*
* This file is part of 'Agit' - an Android Git client.
*
* Agit 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.
*
* Agit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.madgag.agit.diff;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import static android.content.Context.VIBRATOR_SERVICE;
import static android.graphics.Typeface.BOLD;
import static android.graphics.Typeface.create;
import static android.view.Gravity.CENTER;
import static com.madgag.agit.R.id.*;
import static com.madgag.agit.R.layout.diff_seekbar_view;
public class DiffSliderView extends LinearLayout {
private String TAG="DSV";
public static interface OnStateUpdateListener {
void onStateChanged (DiffSliderView diffSliderView, float state);
}
private OnStateUpdateListener stateUpdateListener;
private final TextView beforeTextView,afterTextView;
private final Typeface defaultTypeface, boldTypeFace;
public DiffSliderView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
setGravity(CENTER);
LayoutInflater.from(context).inflate(diff_seekbar_view, this);
beforeTextView = (TextView) findViewById(beforeText);
afterTextView = (TextView) findViewById(afterText);
defaultTypeface = beforeTextView.getTypeface();
boldTypeFace = create(defaultTypeface, BOLD);
SeekBar seekBar = (SeekBar) findViewById(DiffPlayerSeekBar);
DiffSeekBarChangeListener foo = new DiffSeekBarChangeListener((Vibrator) context.getSystemService(VIBRATOR_SERVICE));
seekBar.setOnSeekBarChangeListener(foo);
- seekBar.setProgress(seekBar.getMax());
+ seekBar.setProgress(seekBar.getMax()/2);//This should correctly set the thumb to the middle in the diffview on open
}
public void setStateUpdateListener(OnStateUpdateListener stateUpdateListener) {
this.stateUpdateListener=stateUpdateListener;
}
class DiffSeekBarChangeListener implements OnSeekBarChangeListener {
private final Vibrator vibrator;
public DiffSeekBarChangeListener(Vibrator vibrator) {
this.vibrator = vibrator;
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO - should we animate this movement?
int sector=(int) (unitProgress(seekBar)*3); // 0 ,1 ,2
int progress= (sector * seekBar.getMax()) / 2;
seekBar.setProgress(progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
boolean before=progress==0, after=seekBar.getMax()==progress, middle = seekBar.getMax()/2==progress;
if (before || after || middle) {
vibrator.vibrate(17);
}
// sadly makes the damn seekbar wiggle
// beforeTextView.setTypeface(before?boldTypeFace:defaultTypeface);
// afterTextView.setTypeface(after?boldTypeFace:defaultTypeface);
float unitProgress = unitProgress(seekBar);
notifyTheOthers(unitProgress);
}
private float unitProgress(SeekBar seekBar) {
return ((float)seekBar.getProgress())/seekBar.getMax();
}
}
private void notifyTheOthers(float unitProgress) {
Log.d(TAG, "notifyTheOthers stateUpdateListener="+stateUpdateListener);
if (stateUpdateListener!=null) {
stateUpdateListener.onStateChanged(this, unitProgress);
}
}
}
| true | true | public DiffSliderView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
setGravity(CENTER);
LayoutInflater.from(context).inflate(diff_seekbar_view, this);
beforeTextView = (TextView) findViewById(beforeText);
afterTextView = (TextView) findViewById(afterText);
defaultTypeface = beforeTextView.getTypeface();
boldTypeFace = create(defaultTypeface, BOLD);
SeekBar seekBar = (SeekBar) findViewById(DiffPlayerSeekBar);
DiffSeekBarChangeListener foo = new DiffSeekBarChangeListener((Vibrator) context.getSystemService(VIBRATOR_SERVICE));
seekBar.setOnSeekBarChangeListener(foo);
seekBar.setProgress(seekBar.getMax());
}
| public DiffSliderView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
setGravity(CENTER);
LayoutInflater.from(context).inflate(diff_seekbar_view, this);
beforeTextView = (TextView) findViewById(beforeText);
afterTextView = (TextView) findViewById(afterText);
defaultTypeface = beforeTextView.getTypeface();
boldTypeFace = create(defaultTypeface, BOLD);
SeekBar seekBar = (SeekBar) findViewById(DiffPlayerSeekBar);
DiffSeekBarChangeListener foo = new DiffSeekBarChangeListener((Vibrator) context.getSystemService(VIBRATOR_SERVICE));
seekBar.setOnSeekBarChangeListener(foo);
seekBar.setProgress(seekBar.getMax()/2);//This should correctly set the thumb to the middle in the diffview on open
}
|
diff --git a/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java b/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
index 41c9e96..d85ce90 100644
--- a/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
+++ b/src/java/net/sf/picard/sam/AbstractAlignmentMerger.java
@@ -1,408 +1,408 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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 net.sf.picard.sam;
import net.sf.picard.PicardException;
import net.sf.picard.io.IoUtil;
import net.sf.picard.reference.ReferenceSequenceFileWalker;
import net.sf.picard.util.CigarUtil;
import net.sf.picard.util.Log;
import net.sf.picard.util.PeekableIterator;
import net.sf.samtools.*;
import net.sf.samtools.util.CloseableIterator;
import net.sf.samtools.util.SequenceUtil;
import net.sf.samtools.util.SortingCollection;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Abstract class that coordinates the general task of taking in a set of alignment information,
* possibly in SAM format, possibly in other formats, and merging that with the set of all reads
* for which alignment was attempted, stored in an unmapped SAM file.
*
* The order of processing is as follows:
*
* 1. Get records from the unmapped bam and the alignment data
* 2. Merge the alignment information and public tags ONLY from the aligned SAMRecords
* 3. Do additional modifications -- handle clipping, trimming, etc.
* 4. Fix up mate information on paired reads
* 5. Do a final calculation of the NM and UQ tags.
* 6. Write the records to the output file.
*
* Concrete subclasses which extend AbstractAlignmentMerger should implement getQueryNameSortedAlignedRecords.
* If these records are not in queryname order, mergeAlignment will throw an IllegalStateException.
*
* Subclasses may optionally implement ignoreAlignment(), which can be used to skip over certain alignments.
*
*
* @author [email protected]
*/
public abstract class AbstractAlignmentMerger {
public static final int MAX_RECORDS_IN_RAM = 500000;
private static final char[] RESERVED_ATTRIBUTE_STARTS = {'X','Y', 'Z'};
private final Log log = Log.getInstance(AbstractAlignmentMerger.class);
private final File unmappedBamFile;
private final File targetBamFile;
private SAMSequenceDictionary sequenceDictionary = null;
private ReferenceSequenceFileWalker refSeq = null;
private final boolean clipAdapters;
private final boolean bisulfiteSequence;
private SAMProgramRecord programRecord;
private final boolean alignedReadsOnly;
private final SAMFileHeader header;
private final List<String> attributesToRetain = new ArrayList<String>();
private final File referenceFasta;
private final Integer read1BasesTrimmed;
private final Integer read2BasesTrimmed;
private final List<SamPairUtil.PairOrientation> expectedOrientations;
protected abstract CloseableIterator<SAMRecord> getQuerynameSortedAlignedRecords();
protected boolean ignoreAlignment(SAMRecord sam) { return false; } // default implementation
/**
* Constructor
*
* @param unmappedBamFile The BAM file that was used as the input to the aligner, which will
* include info on all the reads that did not map. Required.
* @param targetBamFile The file to which to write the merged SAM records. Required.
* @param referenceFasta The reference sequence for the map files. Required.
* @param clipAdapters Whether adapters marked in unmapped BAM file should be marked as
* soft clipped in the merged bam. Required.
* @param bisulfiteSequence Whether the reads are bisulfite sequence (used when calculating the
* NM and UQ tags). Required.
* @param alignedReadsOnly Whether to output only those reads that have alignment data
* @param programRecord Program record for taget file SAMRecords created.
* @param attributesToRetain private attributes from the alignment record that should be
* included when merging. This overrides the exclusion of
* attributes whose tags start with the reserved characters
* of X, Y, and Z
* @param read1BasesTrimmed The number of bases trimmed from start of read 1 prior to alignment. Optional.
* @param read2BasesTrimmed The number of bases trimmed from start of read 2 prior to alignment. Optional.
* @param expectedOrientations A List of SamPairUtil.PairOrientations that are expected for
* aligned pairs. Used to determine the properPair flag.
*/
public AbstractAlignmentMerger(final File unmappedBamFile, final File targetBamFile,
final File referenceFasta, final boolean clipAdapters,
final boolean bisulfiteSequence, final boolean alignedReadsOnly,
final SAMProgramRecord programRecord, final List<String> attributesToRetain,
final Integer read1BasesTrimmed, final Integer read2BasesTrimmed,
final List<SamPairUtil.PairOrientation> expectedOrientations) {
IoUtil.assertFileIsReadable(unmappedBamFile);
IoUtil.assertFileIsWritable(targetBamFile);
IoUtil.assertFileIsReadable(referenceFasta);
this.unmappedBamFile = unmappedBamFile;
this.targetBamFile = targetBamFile;
this.referenceFasta = referenceFasta;
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
this.sequenceDictionary = refSeq.getSequenceDictionary();
this.clipAdapters = clipAdapters;
this.bisulfiteSequence = bisulfiteSequence;
this.alignedReadsOnly = alignedReadsOnly;
this.programRecord = programRecord;
this.header = new SAMFileHeader();
header.setSortOrder(SAMFileHeader.SortOrder.coordinate);
if (programRecord != null) {
header.addProgramRecord(programRecord);
}
header.setSequenceDictionary(this.sequenceDictionary);
if (attributesToRetain != null) {
this.attributesToRetain.addAll(attributesToRetain);
}
this.read1BasesTrimmed = read1BasesTrimmed;
this.read2BasesTrimmed = read2BasesTrimmed;
this.expectedOrientations = expectedOrientations;
}
/**
* Merges the alignment data with the non-aligned records from the source BAM file.
*/
public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
- coordinateSorted.add(firstOfPair);
- firstOfPair = rec;
+ throw new PicardException("Second read from pair not found in unmapped bam: " +
+ rec.getReadName());
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
/**
* Checks to see whether the ends of the reads overlap and soft clips reads
* them if necessary.
*/
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) {
// If both reads are mapped, see if we need to clip the ends due to small
// insert size
if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) {
if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag())
{
final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1;
final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2;
// Innies only -- do we need to do anything else about jumping libraries?
if (pos.getAlignmentStart() < neg.getAlignmentEnd()) {
final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd();
final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart();
if (posDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(),
pos.getReadLength() - posDiff + 1));
}
if (negDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(),
neg.getReadLength() - negDiff + 1));
}
}
}
else {
// TODO: What about RR/FF pairs?
}
}
}
/**
* Determines whether two SAMRecords represent the same read
*/
protected boolean isMatch(final SAMRecord unaligned, final SAMRecord aligned) {
return (aligned != null &&
aligned.getReadName().equals(unaligned.getReadName()) &&
(unaligned.getReadPairedFlag() == false ||
aligned.getFirstOfPairFlag() == unaligned.getFirstOfPairFlag()));
}
/**
* Sets the values from the alignment record on the unaligned BAM record. This
* preserves all data from the unaligned record (ReadGroup, NoiseRead status, etc)
* and adds all the alignment info
*
* @param rec The unaligned read record
* @param alignment The alignment record
*/
protected void setValuesFromAlignment(final SAMRecord rec, final SAMRecord alignment) {
for (final SAMRecord.SAMTagAndValue attr : alignment.getAttributes()) {
// Copy over any non-reserved attributes.
if (!isReservedTag(attr.tag) || this.attributesToRetain.contains(attr.tag)) {
rec.setAttribute(attr.tag, attr.value);
}
}
rec.setReadUnmappedFlag(alignment.getReadUnmappedFlag());
rec.setReferenceName(alignment.getReferenceName());
rec.setAlignmentStart(alignment.getAlignmentStart());
rec.setReadNegativeStrandFlag(alignment.getReadNegativeStrandFlag());
if (!alignment.getReadUnmappedFlag()) {
// only aligned reads should have cigar and mapping quality set
rec.setCigar(alignment.getCigar()); // cigar may change when a
// clipCigar called below
rec.setMappingQuality(alignment.getMappingQuality());
}
if (rec.getReadPairedFlag()) {
rec.setProperPairFlag(alignment.getProperPairFlag());
// Mate info and alignment size will get set by the ClippedPairFixer.
}
// If it's on the negative strand, reverse complement the bases
// and reverse the order of the qualities
if (rec.getReadNegativeStrandFlag()) {
SAMRecordUtil.reverseComplement(rec);
}
}
protected void updateCigarForTrimmedOrClippedBases(final SAMRecord rec, final SAMRecord alignment) {
// If the read maps off the end of the alignment, clip it
SAMSequenceRecord refseq = rec.getHeader().getSequence(rec.getReferenceIndex());
if (rec.getAlignmentEnd() > refseq.getSequenceLength()) {
// 1-based index of first base in read to clip.
int clipFrom = refseq.getSequenceLength() - rec.getAlignmentStart() + 1;
List<CigarElement> newCigarElements = CigarUtil.softClipEndOfRead(clipFrom, rec.getCigar().getCigarElements());
rec.setCigar(new Cigar(newCigarElements));
}
// If the read was trimmed or not all the bases were sent for alignment, clip it
int alignmentReadLength = alignment.getReadLength();
int originalReadLength = rec.getReadLength();
int trimmed = (!rec.getReadPairedFlag()) || rec.getFirstOfPairFlag()
? this.read1BasesTrimmed != null ? this.read1BasesTrimmed : 0
: this.read2BasesTrimmed != null ? this.read2BasesTrimmed : 0;
int notWritten = originalReadLength - (alignmentReadLength + trimmed);
rec.setCigar(CigarUtil.addSoftClippedBasesToEndsOfCigar(
rec.getCigar(), rec.getReadNegativeStrandFlag(), notWritten, trimmed));
// If the adapter sequence is marked and clipAdapter is true, ciip it
if (this.clipAdapters && rec.getAttribute(ReservedTagConstants.XT) != null){
CigarUtil.softClip3PrimeEndOfRead(rec, rec.getIntegerAttribute(ReservedTagConstants.XT));
}
}
protected SAMSequenceDictionary getSequenceDictionary() { return this.sequenceDictionary; }
protected SAMProgramRecord getProgramRecord() { return this.programRecord; }
protected void setProgramRecord(SAMProgramRecord pg ) {
this.programRecord = pg;
this.header.addProgramRecord(pg);
}
protected boolean isReservedTag(String tag) {
for (char c : RESERVED_ATTRIBUTE_STARTS) {
if (tag.charAt(0) == c) return true;
}
return false;
}
protected SAMFileHeader getHeader() { return this.header; }
protected void resetRefSeqFileWalker() {
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
}
}
| true | true | public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
coordinateSorted.add(firstOfPair);
firstOfPair = rec;
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
| public void mergeAlignment() {
final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
// Create the sorting collection that will write the records in coordinate order
// to the final bam file
final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
SAMRecord firstOfPair = null;
while (unmappedIterator.hasNext()) {
final SAMRecord rec = unmappedIterator.next();
if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
rec.setHeader(this.header);
// If the next record is a match and is an acceptable alignment, pull the info over to the unmapped record
if (isMatch(rec, nextAligned)) {
if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
setValuesFromAlignment(rec, nextAligned);
updateCigarForTrimmedOrClippedBases(rec, nextAligned);
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
this.programRecord.getProgramGroupId());
}
aligned++;
}
else {
unmapped++;
}
nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
}
else {
unmapped++;
}
// If it's single-end, then just add it if appropriate
if (!rec.getReadPairedFlag()) {
if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
coordinateSorted.add(rec);
}
}
else {
// If it's the first read of a pair, hang on to it until we see its mate next
if (firstOfPair == null) {
firstOfPair = rec;
}
else { // Now we should have the pair, but may not if the aligner used does retain the
// unmapped read from a pair (e.g. Maq)
if (!rec.getReadName().equals(firstOfPair.getReadName())) {
throw new PicardException("Second read from pair not found in unmapped bam: " +
rec.getReadName());
}
else {
// IF at least one of the reads is mapped or we are writing them all
if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
clipForOverlappingReads(rec, firstOfPair);
SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
coordinateSorted.add(firstOfPair);
coordinateSorted.add(rec);
firstOfPair = null;
}
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
// Write the records to the output file in coordinate sorted order,
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
int count = 0;
CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
while (it.hasNext()) {
SAMRecord rec = it.next();
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(),
SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(),
SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
if (++count % 1000000 == 0) {
log.info(count + " SAMRecords written to " + targetBamFile.getName());
}
}
writer.close();
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
|
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/invocationhandler/PartialBeanMethodHandler.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/invocationhandler/PartialBeanMethodHandler.java
index 0148e0ee..ab1e3403 100644
--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/invocationhandler/PartialBeanMethodHandler.java
+++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/invocationhandler/PartialBeanMethodHandler.java
@@ -1,48 +1,48 @@
/*
* 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.deltaspike.core.impl.invocationhandler;
import javassist.util.proxy.MethodHandler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
class PartialBeanMethodHandler<T extends InvocationHandler> implements MethodHandler
{
private final T handlerInstance;
PartialBeanMethodHandler(T handlerInstance)
{
this.handlerInstance = handlerInstance;
}
public Object invoke(Object target, Method method, Method proceedMethod, Object[] arguments) throws Throwable
{
if (proceedMethod != null)
{
return proceedMethod.invoke(target, arguments);
}
- return this.handlerInstance.invoke(this.handlerInstance, method, arguments);
+ return this.handlerInstance.invoke(target, method, arguments);
}
T getHandlerInstance()
{
return this.handlerInstance;
}
}
| true | true | public Object invoke(Object target, Method method, Method proceedMethod, Object[] arguments) throws Throwable
{
if (proceedMethod != null)
{
return proceedMethod.invoke(target, arguments);
}
return this.handlerInstance.invoke(this.handlerInstance, method, arguments);
}
| public Object invoke(Object target, Method method, Method proceedMethod, Object[] arguments) throws Throwable
{
if (proceedMethod != null)
{
return proceedMethod.invoke(target, arguments);
}
return this.handlerInstance.invoke(target, method, arguments);
}
|
diff --git a/common/springext/src/main/java/com/alibaba/citrus/springext/util/ClassCompatibilityAssert.java b/common/springext/src/main/java/com/alibaba/citrus/springext/util/ClassCompatibilityAssert.java
index 79e6e9b5..1b293972 100644
--- a/common/springext/src/main/java/com/alibaba/citrus/springext/util/ClassCompatibilityAssert.java
+++ b/common/springext/src/main/java/com/alibaba/citrus/springext/util/ClassCompatibilityAssert.java
@@ -1,40 +1,40 @@
/*
* Copyright (c) 2002-2012 Alibaba Group Holding Limited.
* 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.alibaba.citrus.springext.util;
import static com.alibaba.citrus.util.Assert.*;
import org.springframework.core.SpringVersion;
/**
* 检查类型兼容性的工具。
*
* @author Michael Zhou
*/
public class ClassCompatibilityAssert {
/** 检查spring版本是否为3.1.x。从这个版本起,和以前的版本在api上有不兼容。 */
public static void assertSpring3_1_x() {
ClassLoader cl = SpringVersion.class.getClassLoader();
try {
cl.loadClass("org.springframework.core.env.Environment");
} catch (ClassNotFoundException e) {
- fail("Unsupported Spring version: %s, required Spring 3.1.x or later", SpringVersion.getVersion());
+ fail("Unsupported Spring version: %s, requires Spring 3.1.x or later", SpringVersion.getVersion());
}
}
}
| true | true | public static void assertSpring3_1_x() {
ClassLoader cl = SpringVersion.class.getClassLoader();
try {
cl.loadClass("org.springframework.core.env.Environment");
} catch (ClassNotFoundException e) {
fail("Unsupported Spring version: %s, required Spring 3.1.x or later", SpringVersion.getVersion());
}
}
| public static void assertSpring3_1_x() {
ClassLoader cl = SpringVersion.class.getClassLoader();
try {
cl.loadClass("org.springframework.core.env.Environment");
} catch (ClassNotFoundException e) {
fail("Unsupported Spring version: %s, requires Spring 3.1.x or later", SpringVersion.getVersion());
}
}
|
diff --git a/pkts-examples/src/main/java/io/pkts/examples/core/CoreExample001.java b/pkts-examples/src/main/java/io/pkts/examples/core/CoreExample001.java
index a9c9f70..98f3b0b 100644
--- a/pkts-examples/src/main/java/io/pkts/examples/core/CoreExample001.java
+++ b/pkts-examples/src/main/java/io/pkts/examples/core/CoreExample001.java
@@ -1,55 +1,55 @@
/**
*
*/
package io.pkts.examples.core;
import io.pkts.PacketHandler;
import io.pkts.Pcap;
import io.pkts.packet.Packet;
import io.pkts.protocol.Protocol;
import java.io.IOException;
/**
* A very simple example that just loads a pcap and prints out the content of
* all UDP packets.
*
* @author [email protected]
*/
public class CoreExample001 {
public static void main(final String[] args) throws IOException {
// Step 1 - obtain a new Pcap instance by supplying an InputStream that points
// to a source that contains your captured traffic. Typically you may
// have stored that traffic in a file so there are a few convenience
// methods for those cases, such as just supplying the name of the
// file as shown below.
final Pcap pcap = Pcap.openStream("my_traffic.pcap");
// Step 2 - Once you have obtained an instance, you want to start
// looping over the content of the pcap. Do this by calling
// the loop function and supply a PacketHandler, which is a
// simple interface with only a single method - nextPacket
pcap.loop(new PacketHandler() {
@Override
- public void nextPacket(final Packet frame) throws IOException {
+ public void nextPacket(final Packet packet) throws IOException {
// Step 3 - For every new packet the FrameHandler will be
// called and you can examine this packet in a few
// different ways. You can e.g. check whether the
// packet contains a particular protocol, such as UDP.
- if (frame.hasProtocol(Protocol.UDP)) {
+ if (packet.hasProtocol(Protocol.UDP)) {
// Step 4 - Now that we know that the packet contains
// a UDP packet we get ask to get the UDP packet
// and once we have it we can just get its
// payload and print it, which is what we are
// doing below.
- System.out.println(frame.getPacket(Protocol.UDP).getPayload());
+ System.out.println(packet.getPacket(Protocol.UDP).getPayload());
}
}
});
}
}
| false | true | public static void main(final String[] args) throws IOException {
// Step 1 - obtain a new Pcap instance by supplying an InputStream that points
// to a source that contains your captured traffic. Typically you may
// have stored that traffic in a file so there are a few convenience
// methods for those cases, such as just supplying the name of the
// file as shown below.
final Pcap pcap = Pcap.openStream("my_traffic.pcap");
// Step 2 - Once you have obtained an instance, you want to start
// looping over the content of the pcap. Do this by calling
// the loop function and supply a PacketHandler, which is a
// simple interface with only a single method - nextPacket
pcap.loop(new PacketHandler() {
@Override
public void nextPacket(final Packet frame) throws IOException {
// Step 3 - For every new packet the FrameHandler will be
// called and you can examine this packet in a few
// different ways. You can e.g. check whether the
// packet contains a particular protocol, such as UDP.
if (frame.hasProtocol(Protocol.UDP)) {
// Step 4 - Now that we know that the packet contains
// a UDP packet we get ask to get the UDP packet
// and once we have it we can just get its
// payload and print it, which is what we are
// doing below.
System.out.println(frame.getPacket(Protocol.UDP).getPayload());
}
}
});
}
| public static void main(final String[] args) throws IOException {
// Step 1 - obtain a new Pcap instance by supplying an InputStream that points
// to a source that contains your captured traffic. Typically you may
// have stored that traffic in a file so there are a few convenience
// methods for those cases, such as just supplying the name of the
// file as shown below.
final Pcap pcap = Pcap.openStream("my_traffic.pcap");
// Step 2 - Once you have obtained an instance, you want to start
// looping over the content of the pcap. Do this by calling
// the loop function and supply a PacketHandler, which is a
// simple interface with only a single method - nextPacket
pcap.loop(new PacketHandler() {
@Override
public void nextPacket(final Packet packet) throws IOException {
// Step 3 - For every new packet the FrameHandler will be
// called and you can examine this packet in a few
// different ways. You can e.g. check whether the
// packet contains a particular protocol, such as UDP.
if (packet.hasProtocol(Protocol.UDP)) {
// Step 4 - Now that we know that the packet contains
// a UDP packet we get ask to get the UDP packet
// and once we have it we can just get its
// payload and print it, which is what we are
// doing below.
System.out.println(packet.getPacket(Protocol.UDP).getPayload());
}
}
});
}
|
diff --git a/app/util/Dicom.java b/app/util/Dicom.java
index d0f4527..4981287 100644
--- a/app/util/Dicom.java
+++ b/app/util/Dicom.java
@@ -1,113 +1,113 @@
package util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import models.Instance;
import models.Series;
import org.dcm4che.data.Dataset;
import org.dcm4che.data.DcmObjectFactory;
import org.dcm4che.dict.Tags;
public class Dicom {
public static String attribute(byte[] dataset, String tag) throws IOException {
Dataset d = DcmObjectFactory.getInstance().newDataset();
d.readFile(new ByteArrayInputStream(dataset), null, -1);
return d.getString(Tags.forName(tag));
}
public static File file(Instance instance) {
return new File(Properties.getArchive(), instance.files.iterator().next().filepath);
}
//
// public static List<File> files(Series series) throws IOException {
// return files(series, null);
// }
//
public static List<File> files(Series series, String echo) throws IOException {
List<File> files = new ArrayList<File>();
for (Instance instance : series.instances) {
File dicom = file(instance);
if (echo == null || dataset(dicom).getString(Tags.EchoTime).equals(echo)) {
files.add(dicom);
}
}
return files;
}
public static File folder(Series series) {
File folder = new File(Properties.getArchive(), series.instances.iterator().next().files.iterator().next().filepath).getParentFile();
if (folder.list().length != series.instances.size()) {
throw new RuntimeException(String.format("Folder contains %s files but series only has %s!", folder.list().length, series.instances.size()));
}
return folder;
}
//retrieve attributes that aren't in the table or blob by looking in the file
public static Dataset dataset(File dicom) throws IOException {
Dataset dataset = DcmObjectFactory.getInstance().newDataset();
dataset.readFile(dicom, null, -1);
return dataset;
}
public static Set<String> echoes(Dataset dataset) {
Set<String> echoes = new LinkedHashSet<String>();
if (dataset.contains(Tags.EchoTime)) {
echoes.add(dataset.getString(Tags.EchoTime));
} else {
for (int i = 0; i < dataset.get(Tags.PerFrameFunctionalGroupsSeq).countItems(); i++) {
- boolean seen = echoes.add(dataset.getItem(Tags.PerFrameFunctionalGroupsSeq, i).getItem(Tags.MREchoSeq).getString(Tags.EffectiveEchoTime));
- if (seen) {
+ boolean unseen = echoes.add(dataset.getItem(Tags.PerFrameFunctionalGroupsSeq, i).getItem(Tags.MREchoSeq).getString(Tags.EffectiveEchoTime));
+ if (!unseen) {
break;
}
}
}
return echoes;
}
public static void anonymise(File from, File to) throws IOException {
Dataset dataset = DcmObjectFactory.getInstance().newDataset();
dataset.readFile(from, null, -1);
dataset.remove(Tags.PatientName);
dataset.remove(Tags.PatientSex);
dataset.remove(Tags.PatientBirthDate);
dataset.remove(Tags.PatientAddress);
dataset.remove(Tags.ReferringPhysicianName);
dataset.remove(Tags.InstitutionName);
dataset.remove(Tags.StationName);
dataset.remove(Tags.ManufacturerModelName);
dataset.writeFile(to, null);
}
private static final List<String> validCUIDs = Arrays.asList("1.2.840.10008.5.1.4.1.1.4", "1.2.840.10008.5.1.4.1.1.4.1", "1.2.840.10008.5.1.4.1.1.7");
public static boolean renderable(Series series) {
return validCUIDs.contains(series.instances.iterator().next().sop_cuid);
}
// public static Dataset privateDataset(Dataset dataset) throws IOException {
// Dataset privateDataset;
// Dataset perFrameFunctionalGroupsSeq = dataset.getItem(Tags.PerFrameFunctionalGroupsSeq);
// if (perFrameFunctionalGroupsSeq.get(Tags.valueOf("(2005,140F)")).hasItems()) {
// privateDataset = perFrameFunctionalGroupsSeq.getItem(Tags.valueOf("(2005,140F)"));
// } else {
// byte[] buf = dataset.getItem(Tags.PerFrameFunctionalGroupsSeq).get(Tags.valueOf("(2005,140F)")).getDataFragment(0).array();
// privateDataset = DcmObjectFactory.getInstance().newDataset();
// privateDataset.readFile(new ByteArrayInputStream(buf), null, -1);
// }
// return privateDataset;
// }
// public static String attribute(Instance instance, String tag) throws IOException {
// Dataset d = DcmObjectFactory.getInstance().newDataset();
// d.readFile(new File(Properties.getString("archive"), instance.files.iterator().next().filepath), null, -1);
// return d.getItem(Tags.SharedFunctionalGroupsSeq).getItem(Tags.MRFOVGeometrySeq).getString(Tags.forName(tag));
// }
}
| true | true | public static Set<String> echoes(Dataset dataset) {
Set<String> echoes = new LinkedHashSet<String>();
if (dataset.contains(Tags.EchoTime)) {
echoes.add(dataset.getString(Tags.EchoTime));
} else {
for (int i = 0; i < dataset.get(Tags.PerFrameFunctionalGroupsSeq).countItems(); i++) {
boolean seen = echoes.add(dataset.getItem(Tags.PerFrameFunctionalGroupsSeq, i).getItem(Tags.MREchoSeq).getString(Tags.EffectiveEchoTime));
if (seen) {
break;
}
}
}
return echoes;
}
| public static Set<String> echoes(Dataset dataset) {
Set<String> echoes = new LinkedHashSet<String>();
if (dataset.contains(Tags.EchoTime)) {
echoes.add(dataset.getString(Tags.EchoTime));
} else {
for (int i = 0; i < dataset.get(Tags.PerFrameFunctionalGroupsSeq).countItems(); i++) {
boolean unseen = echoes.add(dataset.getItem(Tags.PerFrameFunctionalGroupsSeq, i).getItem(Tags.MREchoSeq).getString(Tags.EffectiveEchoTime));
if (!unseen) {
break;
}
}
}
return echoes;
}
|
diff --git a/getap/src/main/java/org/ldv/sio/getap/web/LoginController.java b/getap/src/main/java/org/ldv/sio/getap/web/LoginController.java
index b93a6bf..8f0100c 100644
--- a/getap/src/main/java/org/ldv/sio/getap/web/LoginController.java
+++ b/getap/src/main/java/org/ldv/sio/getap/web/LoginController.java
@@ -1,107 +1,107 @@
package org.ldv.sio.getap.web;
import org.ldv.sio.getap.app.FormAjoutAp;
import org.ldv.sio.getap.app.User;
import org.ldv.sio.getap.app.UserLoginCriteria;
import org.ldv.sio.getap.app.UserSearchCriteria;
import org.ldv.sio.getap.app.service.IFHauthLoginService;
import org.ldv.sio.getap.app.service.IFManagerGeTAP;
import org.ldv.sio.getap.utils.UtilSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Web controller for application actions.
*/
@Controller
@RequestMapping("/login/*")
public class LoginController {
@Autowired
@Qualifier("serviceAuth")
private IFHauthLoginService hauthLoginService;
@Autowired
@Qualifier("DBServiceMangager")
private IFManagerGeTAP manager;
public void setHauthLoginService(IFHauthLoginService hauthLoginService) {
this.hauthLoginService = hauthLoginService;
}
/**
* Default action, displays the login page.
*
* @param UserLoginCriteria
* The criteria to authenticate
*/
@RequestMapping(value = "index", method = RequestMethod.GET)
public void index(UserLoginCriteria userSearchCriteria) {
}
/**
* Valide user puis l'authentifie via le bean injecté hauthLoginService
*
* @param userLoginCriteria
* The criteria to validate for
* @param bindResult
* Holds userLoginCriteria validation errors
* @param model
* Holds the resulting user (is authenticate)
* @return Success or index view
*/
@RequestMapping(value = "authenticate", method = RequestMethod.POST)
public String authenticate(FormAjoutAp formAjout,
UserLoginCriteria userLoginCriteria, BindingResult bindResult,
Model model, UserSearchCriteria userSearchCriteria) {
if (userLoginCriteria.getLogin() == null
|| "".equals(userLoginCriteria.getLogin().trim())) {
bindResult.rejectValue("login", "required",
"SVP un identifiant est attendu !");
}
if (bindResult.hasErrors()) {
return "login/index";
} else {
User user = hauthLoginService.getAuthUser(userLoginCriteria);
if (user == null) {
bindResult.rejectValue("login", "required",
"SVP entrez un identifiant valide");
return "login/index";
}
UtilSession.setUserInSession(user);
UtilSession.setAnneeScolaireInSession("2011-2012");
model.addAttribute("userAuth", user);
User userIn = UtilSession.getUserInSession();
if (userIn.getRole().equals("prof-principal")) {
model.addAttribute("lesClasses",
manager.getAllClasseByProf(userIn.getId()));
model.addAttribute("lesEleves", manager.getAllEleveByClasse());
model.addAttribute("lesAP", manager.getApByType());
} else if (userIn.getRole().equals("admin")) {
model.addAttribute("lesAP", manager.getAllAP());
}
- return "login/authenticate";
+ return "redirect:/app/" + userIn.getRole() + "/index";
}
}
/**
* supprime user de la session, et retourne au login
*
* @param userLoginCriteria
* (pour fournir cette instance à la vue 'login/index')
* @return Success view
*/
@RequestMapping(value = "logout", method = RequestMethod.GET)
public String logout(UserLoginCriteria userLoginCriteria) {
UtilSession.setUserInSession(null);
return "login/index";
}
}
| true | true | public String authenticate(FormAjoutAp formAjout,
UserLoginCriteria userLoginCriteria, BindingResult bindResult,
Model model, UserSearchCriteria userSearchCriteria) {
if (userLoginCriteria.getLogin() == null
|| "".equals(userLoginCriteria.getLogin().trim())) {
bindResult.rejectValue("login", "required",
"SVP un identifiant est attendu !");
}
if (bindResult.hasErrors()) {
return "login/index";
} else {
User user = hauthLoginService.getAuthUser(userLoginCriteria);
if (user == null) {
bindResult.rejectValue("login", "required",
"SVP entrez un identifiant valide");
return "login/index";
}
UtilSession.setUserInSession(user);
UtilSession.setAnneeScolaireInSession("2011-2012");
model.addAttribute("userAuth", user);
User userIn = UtilSession.getUserInSession();
if (userIn.getRole().equals("prof-principal")) {
model.addAttribute("lesClasses",
manager.getAllClasseByProf(userIn.getId()));
model.addAttribute("lesEleves", manager.getAllEleveByClasse());
model.addAttribute("lesAP", manager.getApByType());
} else if (userIn.getRole().equals("admin")) {
model.addAttribute("lesAP", manager.getAllAP());
}
return "login/authenticate";
}
}
| public String authenticate(FormAjoutAp formAjout,
UserLoginCriteria userLoginCriteria, BindingResult bindResult,
Model model, UserSearchCriteria userSearchCriteria) {
if (userLoginCriteria.getLogin() == null
|| "".equals(userLoginCriteria.getLogin().trim())) {
bindResult.rejectValue("login", "required",
"SVP un identifiant est attendu !");
}
if (bindResult.hasErrors()) {
return "login/index";
} else {
User user = hauthLoginService.getAuthUser(userLoginCriteria);
if (user == null) {
bindResult.rejectValue("login", "required",
"SVP entrez un identifiant valide");
return "login/index";
}
UtilSession.setUserInSession(user);
UtilSession.setAnneeScolaireInSession("2011-2012");
model.addAttribute("userAuth", user);
User userIn = UtilSession.getUserInSession();
if (userIn.getRole().equals("prof-principal")) {
model.addAttribute("lesClasses",
manager.getAllClasseByProf(userIn.getId()));
model.addAttribute("lesEleves", manager.getAllEleveByClasse());
model.addAttribute("lesAP", manager.getApByType());
} else if (userIn.getRole().equals("admin")) {
model.addAttribute("lesAP", manager.getAllAP());
}
return "redirect:/app/" + userIn.getRole() + "/index";
}
}
|
diff --git a/src/java/org/joshy/html/app/browser/BrowserMenuBar.java b/src/java/org/joshy/html/app/browser/BrowserMenuBar.java
index 1fc4e3f4..2c415dc2 100755
--- a/src/java/org/joshy/html/app/browser/BrowserMenuBar.java
+++ b/src/java/org/joshy/html/app/browser/BrowserMenuBar.java
@@ -1,247 +1,247 @@
package org.joshy.html.app.browser;
import com.pdoubleya.xhtmlrenderer.css.bridge.XRStyleReference;
import org.joshy.u;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.logging.*;
import org.joshy.html.*;
import org.joshy.html.swing.*;
import java.io.File;
public class BrowserMenuBar extends JMenuBar {
public static Logger logger = Logger.getLogger("app.browser");
BrowserStartup root;
JMenu file;
JMenu edit;
JMenu view;
JMenu go;
JMenuItem view_source;
JMenu debug;
JMenu demos;
public BrowserMenuBar(BrowserStartup root) {
this.root = root;
logger.setLevel(Level.OFF);
}
public void init() {
file = new JMenu("File");
file.setMnemonic('F');
debug = new JMenu("Debug");
debug.setMnemonic('B');
demos = new JMenu("Demos");
demos.setMnemonic('D');
edit = new JMenu("Edit");
edit.setMnemonic('E');
view = new JMenu("View");
view.setMnemonic('V');
view_source = new JMenuItem("Page Source");
view_source.setEnabled(false);
view.add(root.actions.stop);
view.add(root.actions.refresh);
view.add(root.actions.reload);
go = new JMenu("Go");
go.setMnemonic('G');
}
public void createLayout() {
file.add(root.actions.open_file);
file.add(root.actions.quit);
add(file);
edit.add(root.actions.cut);
edit.add(root.actions.copy);
edit.add(root.actions.paste);
add(edit);
view.add(view_source);
add(view);
go.add(root.actions.forward);
go.add(root.actions.backward);
add(go);
// CLEAN
//demos.add(new LoadAction("Bad Page","demo:demos/allclasses-noframe.xhtml"));
demos.add(new LoadAction("Borders","demo:demos/border.xhtml"));
demos.add(new LoadAction("Backgrounds","demo:demos/background.xhtml"));
demos.add(new LoadAction("Paragraph","demo:demos/paragraph.xhtml"));
demos.add(new LoadAction("Line Breaking","demo:demos/breaking.xhtml"));
demos.add(new LoadAction("Forms","demo:demos/forms.xhtml"));
demos.add(new LoadAction("Headers","demo:demos/header.xhtml"));
demos.add(new LoadAction("Nested Divs","demo:demos/nested.xhtml"));
demos.add(new LoadAction("Selectors","demo:demos/selectors.xhtml"));
demos.add(new LoadAction("Images","demo:demos/image.xhtml"));
demos.add(new LoadAction("Lists","demo:demos/list.xhtml"));
- demos.add(new LoadAction("Tables","demo:demos/table.xhtml"));
+// demos.add(new LoadAction("Tables","demo:demos/table.xhtml"));
try {
demos.add(new LoadAction("File Listing (Win)","file:///c:"));
demos.add(new LoadAction("File Listing (Unix)","file:///"));
} catch (Exception ex) {
u.p(ex);
}
add(demos);
JMenu debugShow = new JMenu("Show");
debug.add(debugShow);
debugShow.setMnemonic('S');
debugShow.add(new JCheckBoxMenuItem(new BoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new LineBoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new InlineBoxesAction()));
debug.add(new ShowDOMInspectorAction());
debug.add(new AbstractAction("Validation Console") {
public void actionPerformed(ActionEvent evt) {
if(root.validation_console == null) {
root.validation_console = new JFrame("Validation Console");
JFrame frame = root.validation_console;
JTextArea jta = new JTextArea();
root.error_handler.setTextArea(jta);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(jta),"Center");
JButton close = new JButton("Close");
frame.getContentPane().add(close,"South");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
root.validation_console.setVisible(false);
}
});
frame.pack();
frame.setSize(200,400);
}
root.validation_console.setVisible(true);
}
});
add(debug);
}
class ShowDOMInspectorAction extends AbstractAction {
private DOMInspector inspector;
private JFrame inspectorFrame;
ShowDOMInspectorAction() {
super("DOM Tree Inspector");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_D));
}
public void actionPerformed(ActionEvent evt) {
if ( inspectorFrame == null ) {
inspectorFrame = new JFrame("DOM Tree Inspector");
}
if ( inspector == null ) {
// inspectorFrame = new JFrame("DOM Tree Inspector");
// CLEAN: this is more complicated than it needs to be
// DOM Tree Inspector needs to work with either CSSBank
// or XRStyleReference--implementations are not perfectly
// so we have different constructors
if ( root.panel.view.c.css instanceof CSSBank )
inspector = new DOMInspector(root.panel.view.doc);
else
inspector = new DOMInspector(root.panel.view.doc, root.panel.view.c, (XRStyleReference)root.panel.view.c.css);
inspectorFrame.getContentPane().add(inspector);
inspectorFrame.pack();
inspectorFrame.setSize(500,600);
inspectorFrame.show();
} else {
if ( root.panel.view.c.css instanceof CSSBank )
inspector.setForDocument(root.panel.view.doc);
else
inspector.setForDocument(root.panel.view.doc, root.panel.view.c, (XRStyleReference)root.panel.view.c.css);
}
inspectorFrame.show();
}
}
class BoxOutlinesAction extends AbstractAction {
BoxOutlinesAction() {
super("Show Box Outlines");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_B));
}
public void actionPerformed(ActionEvent evt) {
root.panel.view.c.debug_draw_boxes = !root.panel.view.c.debug_draw_boxes;
root.panel.view.repaint();
}
}
class LineBoxOutlinesAction extends AbstractAction {
LineBoxOutlinesAction() {
super("Show Line Box Outlines");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_L));
}
public void actionPerformed(ActionEvent evt) {
root.panel.view.c.debug_draw_line_boxes = !root.panel.view.c.debug_draw_line_boxes;
root.panel.view.repaint();
}
}
class InlineBoxesAction extends AbstractAction {
InlineBoxesAction() {
super("Show Inline Boxes");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_I));
}
public void actionPerformed(ActionEvent evt) {
root.panel.view.c.debug_draw_inline_boxes = !root.panel.view.c.debug_draw_inline_boxes;
root.panel.view.repaint();
}
}
public void createActions() {
SelectionMouseListener ma = new SelectionMouseListener();
root.panel.view.addMouseListener(ma);
root.panel.view.addMouseMotionListener(ma);
logger.info("added a mouse motion listener: " + ma);
}
class LoadAction extends AbstractAction {
protected String url;
public LoadAction(String name, String url) {
super(name);
this.url = url;
}
public void actionPerformed(ActionEvent evt) {
try {
root.panel.loadPage(url);
} catch (Exception ex) {
u.p(ex);
}
}
}
}
class EmptyAction extends AbstractAction {
public EmptyAction(String name, int accel) {
this(name);
putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(accel,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
}
public EmptyAction(String name) {
super(name);
}
public void actionPerformed(ActionEvent evt) {
}
}
| true | true | public void createLayout() {
file.add(root.actions.open_file);
file.add(root.actions.quit);
add(file);
edit.add(root.actions.cut);
edit.add(root.actions.copy);
edit.add(root.actions.paste);
add(edit);
view.add(view_source);
add(view);
go.add(root.actions.forward);
go.add(root.actions.backward);
add(go);
// CLEAN
//demos.add(new LoadAction("Bad Page","demo:demos/allclasses-noframe.xhtml"));
demos.add(new LoadAction("Borders","demo:demos/border.xhtml"));
demos.add(new LoadAction("Backgrounds","demo:demos/background.xhtml"));
demos.add(new LoadAction("Paragraph","demo:demos/paragraph.xhtml"));
demos.add(new LoadAction("Line Breaking","demo:demos/breaking.xhtml"));
demos.add(new LoadAction("Forms","demo:demos/forms.xhtml"));
demos.add(new LoadAction("Headers","demo:demos/header.xhtml"));
demos.add(new LoadAction("Nested Divs","demo:demos/nested.xhtml"));
demos.add(new LoadAction("Selectors","demo:demos/selectors.xhtml"));
demos.add(new LoadAction("Images","demo:demos/image.xhtml"));
demos.add(new LoadAction("Lists","demo:demos/list.xhtml"));
demos.add(new LoadAction("Tables","demo:demos/table.xhtml"));
try {
demos.add(new LoadAction("File Listing (Win)","file:///c:"));
demos.add(new LoadAction("File Listing (Unix)","file:///"));
} catch (Exception ex) {
u.p(ex);
}
add(demos);
JMenu debugShow = new JMenu("Show");
debug.add(debugShow);
debugShow.setMnemonic('S');
debugShow.add(new JCheckBoxMenuItem(new BoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new LineBoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new InlineBoxesAction()));
debug.add(new ShowDOMInspectorAction());
debug.add(new AbstractAction("Validation Console") {
public void actionPerformed(ActionEvent evt) {
if(root.validation_console == null) {
root.validation_console = new JFrame("Validation Console");
JFrame frame = root.validation_console;
JTextArea jta = new JTextArea();
root.error_handler.setTextArea(jta);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(jta),"Center");
JButton close = new JButton("Close");
frame.getContentPane().add(close,"South");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
root.validation_console.setVisible(false);
}
});
frame.pack();
frame.setSize(200,400);
}
root.validation_console.setVisible(true);
}
});
add(debug);
}
| public void createLayout() {
file.add(root.actions.open_file);
file.add(root.actions.quit);
add(file);
edit.add(root.actions.cut);
edit.add(root.actions.copy);
edit.add(root.actions.paste);
add(edit);
view.add(view_source);
add(view);
go.add(root.actions.forward);
go.add(root.actions.backward);
add(go);
// CLEAN
//demos.add(new LoadAction("Bad Page","demo:demos/allclasses-noframe.xhtml"));
demos.add(new LoadAction("Borders","demo:demos/border.xhtml"));
demos.add(new LoadAction("Backgrounds","demo:demos/background.xhtml"));
demos.add(new LoadAction("Paragraph","demo:demos/paragraph.xhtml"));
demos.add(new LoadAction("Line Breaking","demo:demos/breaking.xhtml"));
demos.add(new LoadAction("Forms","demo:demos/forms.xhtml"));
demos.add(new LoadAction("Headers","demo:demos/header.xhtml"));
demos.add(new LoadAction("Nested Divs","demo:demos/nested.xhtml"));
demos.add(new LoadAction("Selectors","demo:demos/selectors.xhtml"));
demos.add(new LoadAction("Images","demo:demos/image.xhtml"));
demos.add(new LoadAction("Lists","demo:demos/list.xhtml"));
// demos.add(new LoadAction("Tables","demo:demos/table.xhtml"));
try {
demos.add(new LoadAction("File Listing (Win)","file:///c:"));
demos.add(new LoadAction("File Listing (Unix)","file:///"));
} catch (Exception ex) {
u.p(ex);
}
add(demos);
JMenu debugShow = new JMenu("Show");
debug.add(debugShow);
debugShow.setMnemonic('S');
debugShow.add(new JCheckBoxMenuItem(new BoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new LineBoxOutlinesAction()));
debugShow.add(new JCheckBoxMenuItem(new InlineBoxesAction()));
debug.add(new ShowDOMInspectorAction());
debug.add(new AbstractAction("Validation Console") {
public void actionPerformed(ActionEvent evt) {
if(root.validation_console == null) {
root.validation_console = new JFrame("Validation Console");
JFrame frame = root.validation_console;
JTextArea jta = new JTextArea();
root.error_handler.setTextArea(jta);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JScrollPane(jta),"Center");
JButton close = new JButton("Close");
frame.getContentPane().add(close,"South");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
root.validation_console.setVisible(false);
}
});
frame.pack();
frame.setSize(200,400);
}
root.validation_console.setVisible(true);
}
});
add(debug);
}
|
diff --git a/java/src/com/rdio/simple/RdioApacheClient.java b/java/src/com/rdio/simple/RdioApacheClient.java
index d7e70fa..4c3fe5b 100644
--- a/java/src/com/rdio/simple/RdioApacheClient.java
+++ b/java/src/com/rdio/simple/RdioApacheClient.java
@@ -1,57 +1,57 @@
package com.rdio.simple;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class RdioApacheClient extends RdioClient {
public RdioApacheClient(RdioClient.Consumer consumer) {
super(consumer);
}
public RdioApacheClient(RdioClient.Consumer consumer, RdioClient.Token accessToken) {
super(consumer, accessToken);
}
@Override
protected String signedPost(String url, Parameters params, RdioClient.Token token) throws IOException, RdioException {
return signedPost(url, params, token, new DefaultHttpClient());
}
protected String signedPost(String url, Parameters params, RdioClient.Token token, HttpClient client) throws IOException, RdioException {
String auth;
if (token == null) {
auth = Om.sign(consumer.key, consumer.secret, url, params, null, null, "POST", null);
} else {
auth = Om.sign(consumer.key, consumer.secret, url, params, token.token, token.secret, "POST", null);
}
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(params.toPercentEncoded()));
- post.addHeader("Cache-Control", "no-tranform");
+ post.addHeader("Cache-Control", "no-transform");
post.addHeader("Authorization", auth);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String error = "Request failed with status " + response.getStatusLine();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthorizationException(error);
}
throw new RdioException(error);
}
HttpEntity entity = response.getEntity();
if (entity == null) {
String error = "Null entity in response";
throw new RdioException(error);
}
return EntityUtils.toString(entity);
}
}
| true | true | protected String signedPost(String url, Parameters params, RdioClient.Token token, HttpClient client) throws IOException, RdioException {
String auth;
if (token == null) {
auth = Om.sign(consumer.key, consumer.secret, url, params, null, null, "POST", null);
} else {
auth = Om.sign(consumer.key, consumer.secret, url, params, token.token, token.secret, "POST", null);
}
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(params.toPercentEncoded()));
post.addHeader("Cache-Control", "no-tranform");
post.addHeader("Authorization", auth);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String error = "Request failed with status " + response.getStatusLine();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthorizationException(error);
}
throw new RdioException(error);
}
HttpEntity entity = response.getEntity();
if (entity == null) {
String error = "Null entity in response";
throw new RdioException(error);
}
return EntityUtils.toString(entity);
}
| protected String signedPost(String url, Parameters params, RdioClient.Token token, HttpClient client) throws IOException, RdioException {
String auth;
if (token == null) {
auth = Om.sign(consumer.key, consumer.secret, url, params, null, null, "POST", null);
} else {
auth = Om.sign(consumer.key, consumer.secret, url, params, token.token, token.secret, "POST", null);
}
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(params.toPercentEncoded()));
post.addHeader("Cache-Control", "no-transform");
post.addHeader("Authorization", auth);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
String error = "Request failed with status " + response.getStatusLine();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
throw new AuthorizationException(error);
}
throw new RdioException(error);
}
HttpEntity entity = response.getEntity();
if (entity == null) {
String error = "Null entity in response";
throw new RdioException(error);
}
return EntityUtils.toString(entity);
}
|
diff --git a/src/com/meterware/httpunit/WebConversation.java b/src/com/meterware/httpunit/WebConversation.java
index 85da1fb..886d06c 100644
--- a/src/com/meterware/httpunit/WebConversation.java
+++ b/src/com/meterware/httpunit/WebConversation.java
@@ -1,105 +1,103 @@
package com.meterware.httpunit;
/********************************************************************************************************************
* $Id$
*
* Copyright (c) 2000-2004, Russell Gold
*
* 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.
*
*******************************************************************************************************************/
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Dictionary;
import java.util.Enumeration;
/**
* The context for a series of HTTP requests. This class manages cookies used to maintain
* session context, computes relative URLs, and generally emulates the browser behavior
* needed to build an automated test of a web site.
*
* @author Russell Gold
**/
public class WebConversation extends WebClient {
/**
* Creates a new web conversation.
**/
public WebConversation() {
}
//---------------------------------- protected members --------------------------------
/**
* Creates a web response object which represents the response to the specified web request.
**/
protected WebResponse newResponse( WebRequest request, FrameSelector targetFrame ) throws MalformedURLException, IOException {
URLConnection connection = openConnection( getRequestURL( request ) );
if (HttpUnitOptions.isLoggingHttpHeaders()) {
String urlString = request.getURLString();
- String rawUrl = request.getURL().toExternalForm();
- String target = rawUrl.substring( 0, rawUrl.indexOf( urlString ) );
- System.out.println( "\nConnecting to " + target );
+ System.out.println( "\nConnecting to " + request.getURL().getHost() );
System.out.println( "Sending:: " + request.getMethod() + " " + urlString );
}
sendHeaders( connection, getHeaderFields( request.getURL() ) );
sendHeaders( connection, request.getHeaderDictionary() );
request.completeRequest( connection );
return new HttpWebResponse( this, targetFrame, request, connection, getExceptionsThrownOnErrorStatus() );
}
private URL getRequestURL( WebRequest request ) throws MalformedURLException {
DNSListener dnsListener = getClientProperties().getDnsListener();
if (dnsListener == null) return request.getURL();
String hostName = request.getURL().getHost();
String portPortion = request.getURL().getPort() == -1 ? "" : (":" + request.getURL().getPort());
setHeaderField( "Host", hostName + portPortion );
String actualHost = dnsListener.getIpAddress( hostName );
if (HttpUnitOptions.isLoggingHttpHeaders()) System.out.println( "Rerouting request to :: " + actualHost );
return new URL( request.getURL().getProtocol(), actualHost, request.getURL().getPort(), request.getURL().getFile() );
}
//---------------------------------- private members --------------------------------
private URLConnection openConnection( URL url ) throws MalformedURLException, IOException {
URLConnection connection = url.openConnection();
if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).setInstanceFollowRedirects( false );
connection.setUseCaches( false );
return connection;
}
private void sendHeaders( URLConnection connection, Dictionary headers ) {
for (Enumeration e = headers.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
connection.setRequestProperty( key, (String) headers.get( key ) );
if (HttpUnitOptions.isLoggingHttpHeaders()) {
System.out.println( "Sending:: " + key + ": " + connection.getRequestProperty( key ) );
}
}
}
}
| true | true | protected WebResponse newResponse( WebRequest request, FrameSelector targetFrame ) throws MalformedURLException, IOException {
URLConnection connection = openConnection( getRequestURL( request ) );
if (HttpUnitOptions.isLoggingHttpHeaders()) {
String urlString = request.getURLString();
String rawUrl = request.getURL().toExternalForm();
String target = rawUrl.substring( 0, rawUrl.indexOf( urlString ) );
System.out.println( "\nConnecting to " + target );
System.out.println( "Sending:: " + request.getMethod() + " " + urlString );
}
sendHeaders( connection, getHeaderFields( request.getURL() ) );
sendHeaders( connection, request.getHeaderDictionary() );
request.completeRequest( connection );
return new HttpWebResponse( this, targetFrame, request, connection, getExceptionsThrownOnErrorStatus() );
}
| protected WebResponse newResponse( WebRequest request, FrameSelector targetFrame ) throws MalformedURLException, IOException {
URLConnection connection = openConnection( getRequestURL( request ) );
if (HttpUnitOptions.isLoggingHttpHeaders()) {
String urlString = request.getURLString();
System.out.println( "\nConnecting to " + request.getURL().getHost() );
System.out.println( "Sending:: " + request.getMethod() + " " + urlString );
}
sendHeaders( connection, getHeaderFields( request.getURL() ) );
sendHeaders( connection, request.getHeaderDictionary() );
request.completeRequest( connection );
return new HttpWebResponse( this, targetFrame, request, connection, getExceptionsThrownOnErrorStatus() );
}
|
diff --git a/src/core/org/luaj/lib/PackageLib.java b/src/core/org/luaj/lib/PackageLib.java
index b491ae9..7cf165c 100644
--- a/src/core/org/luaj/lib/PackageLib.java
+++ b/src/core/org/luaj/lib/PackageLib.java
@@ -1,419 +1,419 @@
/*******************************************************************************
* Copyright (c) 2007 LuaJ. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
package org.luaj.lib;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Vector;
import org.luaj.vm.CallInfo;
import org.luaj.vm.LBoolean;
import org.luaj.vm.LFunction;
import org.luaj.vm.LNil;
import org.luaj.vm.LString;
import org.luaj.vm.LTable;
import org.luaj.vm.LValue;
import org.luaj.vm.Lua;
import org.luaj.vm.LuaState;
import org.luaj.vm.Platform;
public class PackageLib extends LFunction {
public static final String DEFAULT_LUA_PATH = "?.luac;?.lua";
public static InputStream STDIN = null;
public static PrintStream STDOUT = System.out;
public static LTable LOADED = null;
private static final LString _M = new LString("_M");
private static final LString _NAME = new LString("_NAME");
private static final LString _PACKAGE = new LString("_PACKAGE");
private static final LString _DOT = new LString(".");
private static final LString _EMPTY = new LString("");
private static final LString __INDEX = new LString("__index");
private static final LString _LOADERS = new LString("loaders");
private static final LString _PRELOAD = new LString("preload");
private static final LString _PATH = new LString("path");
private static final LValue _SENTINEL = _EMPTY;
private static final LString _LUA_PATH = new LString(DEFAULT_LUA_PATH);
private static final String[] NAMES = {
"package",
"module",
"require",
"loadlib",
"seeall",
"preload_loader",
"lua_loader",
"java_loader",
};
private static final int INSTALL = 0;
private static final int MODULE = 1;
private static final int REQUIRE = 2;
private static final int LOADLIB = 3;
private static final int SEEALL = 4;
private static final int PRELOAD_LOADER = 5;
private static final int LUA_LOADER = 6;
private static final int JAVA_LOADER = 7;
// all functions in package share this environment
private static LTable pckg;
public static void install( LTable globals ) {
for ( int i=1; i<=REQUIRE; i++ )
globals.put( NAMES[i], new PackageLib(i) );
pckg = new LTable();
for ( int i=LOADLIB; i<=SEEALL; i++ )
pckg.put( NAMES[i], new PackageLib(i) );
LOADED = new LTable();
pckg.put( "loaded", LOADED );
pckg.put( _PRELOAD, new LTable() );
LTable loaders = new LTable(3,0);
for ( int i=PRELOAD_LOADER; i<=JAVA_LOADER; i++ )
loaders.luaInsertPos(0, new PackageLib(i) );
pckg.put( "loaders", loaders );
pckg.put( _PATH, _LUA_PATH );
globals.put( "package", pckg );
}
public static void setLuaPath( String newLuaPath ) {
pckg.put( _PATH, new LString(newLuaPath) );
}
private final int id;
private PackageLib( int id ) {
this.id = id;
}
public String toString() {
return NAMES[id]+"()";
}
public boolean luaStackCall( LuaState vm ) {
switch ( id ) {
case INSTALL:
install(vm._G);
break;
case MODULE:
module(vm);
break;
case REQUIRE:
require(vm);
break;
case LOADLIB:
loadlib(vm);
break;
case SEEALL: {
if ( ! vm.istable(2) )
vm.error( "table expected, got "+vm.typename(2) );
LTable t = vm.totable(2);
LTable m = t.luaGetMetatable();
if ( m == null )
t.luaSetMetatable(m = new LTable());
m.put(__INDEX, vm._G);
vm.resettop();
break;
}
case PRELOAD_LOADER: {
loader_preload(vm);
break;
}
case LUA_LOADER: {
loader_Lua(vm);
break;
}
case JAVA_LOADER: {
loader_Java(vm);
break;
}
default:
LuaState.vmerror( "bad package id" );
}
return false;
}
// ======================== Module, Package loading =============================
/**
* module (name [, ...])
*
* Creates a module. If there is a table in package.loaded[name], this table
* is the module. Otherwise, if there is a global table t with the given
* name, this table is the module. Otherwise creates a new table t and sets
* it as the value of the global name and the value of package.loaded[name].
* This function also initializes t._NAME with the given name, t._M with the
* module (t itself), and t._PACKAGE with the package name (the full module
* name minus last component; see below). Finally, module sets t as the new
* environment of the current function and the new value of
* package.loaded[name], so that require returns t.
*
* If name is a compound name (that is, one with components separated by
* dots), module creates (or reuses, if they already exist) tables for each
* component. For instance, if name is a.b.c, then module stores the module
* table in field c of field b of global a.
*
* This function may receive optional options after the module name, where
* each option is a function to be applied over the module.
*/
public static void module(LuaState vm) {
LString modname = vm.tolstring(2);
int n = vm.gettop();
LValue value = LOADED.get(modname);
LTable module;
if ( value.luaGetType() != Lua.LUA_TTABLE ) { /* not found? */
/* try global variable (and create one if it does not exist) */
module = findtable( vm._G, modname );
if ( module == null )
vm.error( "name conflict for module '"+modname+"'" );
LOADED.luaSetTable(vm, LOADED, modname, module);
} else {
module = (LTable) value;
}
/* check whether table already has a _NAME field */
LValue name = module.luaGetTable(vm, module, _NAME);
if ( name.isNil() ) {
modinit( vm, module, modname );
}
// set the environment of the current function
CallInfo ci = vm.getStackFrame(0);
ci.closure.env = module;
// apply the functions
for ( int i=3; i<=n; i++ ) {
vm.pushvalue( i ); /* get option (a function) */
vm.pushlvalue( module ); /* module */
vm.call( 1, 0 );
}
// returns no results
vm.resettop();
}
/**
*
* @param table the table at which to start the search
* @param fname the name to look up or create, such as "abc.def.ghi"
* @return the table for that name, possible a new one, or null if a non-table has that name already.
*/
private static LTable findtable(LTable table, LString fname) {
int b, e=(-1);
do {
e = fname.indexOf(_DOT, b=e+1 );
if ( e < 0 )
e = fname.m_length;
LString key = fname.substring(b, e);
LValue val = table.get(key);
if ( val.isNil() ) { /* no such field? */
LTable field = new LTable(); /* new table for field */
table.put(key, field);
table = field;
} else if ( val.luaGetType() != Lua.LUA_TTABLE ) { /* field has a non-table value? */
return null;
} else {
table = (LTable) val;
}
} while ( e < fname.m_length );
return table;
}
private static void modinit(LuaState vm, LTable module, LString modname) {
/* module._M = module */
module.luaSetTable(vm, module, _M, module);
int e = modname.lastIndexOf(_DOT);
module.luaSetTable(vm, module, _NAME, modname );
module.luaSetTable(vm, module, _PACKAGE, (e<0? _EMPTY: modname.substring(0,e+1)) );
}
/**
* require (modname)
*
* Loads the given module. The function starts by looking into the package.loaded table to
* determine whether modname is already loaded. If it is, then require returns the value
* stored at package.loaded[modname]. Otherwise, it tries to find a loader for the module.
*
* To find a loader, require is guided by the package.loaders array. By changing this array,
* we can change how require looks for a module. The following explanation is based on the
* default configuration for package.loaders.
*
* First require queries package.preload[modname]. If it has a value, this value
* (which should be a function) is the loader. Otherwise require searches for a Lua loader
* using the path stored in package.path. If that also fails, it searches for a C loader
* using the path stored in package.cpath. If that also fails, it tries an all-in-one loader
* (see package.loaders).
*
* Once a loader is found, require calls the loader with a single argument, modname.
* If the loader returns any value, require assigns the returned value to package.loaded[modname].
* If the loader returns no value and has not assigned any value to package.loaded[modname],
* then require assigns true to this entry. In any case, require returns the final value of
* package.loaded[modname].
*
* If there is any error loading or running the module, or if it cannot find any loader for
* the module, then require signals an error.
*/
public void require( LuaState vm ) {
LString name = vm.tolstring(2);
LValue loaded = LOADED.get(name);
if ( loaded.toJavaBoolean() ) {
if ( loaded == _SENTINEL )
vm.error("loop or previous error loading module '"+name+"'");
vm.resettop();
vm.pushlvalue( loaded );
return;
}
vm.resettop();
/* else must load it; iterate over available loaders */
LValue val = pckg.luaGetTable(vm, pckg, _LOADERS);
if ( ! val.isTable() )
vm.error( "'package.loaders' must be a table" );
vm.pushlvalue(val);
Vector v = new Vector();
for ( int i=1; true; i++ ) {
vm.rawgeti(1, i);
if ( vm.isnil(-1) ) {
vm.error( "module '"+name+"' not found: "+v );
}
/* call loader with module name as argument */
vm.pushlstring(name);
vm.call(1, 1);
if ( vm.isfunction(-1) )
break; /* module loaded successfully */
if ( vm.isstring(-1) ) /* loader returned error message? */
v.addElement(vm.tolstring(-1)); /* accumulate it */
vm.pop(1);
}
// load the module using the loader
LOADED.luaSetTable(vm, LOADED, name, _SENTINEL);
vm.pushlstring( name ); /* pass name as argument to module */
vm.call( 1, 1 ); /* run loaded module */
if ( ! vm.isnil(-1) ) /* non-nil return? */
LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */
- if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */
- LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */
- vm.pushboolean(true);
+ LValue result = LOADED.luaGetTable(vm, LOADED, name);
+ if ( result == _SENTINEL ) { /* module did not set a value? */
+ LOADED.luaSetTable(vm, LOADED, name, result=LBoolean.TRUE ); /* _LOADED[name] = true */
}
- vm.replace(1);
- vm.settop(1);
+ vm.resettop();
+ vm.pushlvalue(result);
}
public static void loadlib( LuaState vm ) {
vm.error( "loadlib not implemented" );
}
private void loader_preload( LuaState vm ) {
LString name = vm.tolstring(2);
LValue preload = pckg.luaGetTable(vm, pckg, _PRELOAD);
if ( ! preload.isTable() )
vm.error("package.preload '"+name+"' must be a table");
LValue val = preload.luaGetTable(vm, preload, name);
if ( val.isNil() )
vm.pushstring("\n\tno field package.preload['"+name+"']");
vm.resettop();
vm.pushlvalue(val);
}
private void loader_Lua( LuaState vm ) {
String name = vm.tostring(2);
InputStream is = findfile( vm, name, _PATH );
if ( is != null ) {
String filename = vm.tostring(-1);
if ( ! BaseLib.loadis(vm, is, filename) )
loaderror( vm, filename );
}
vm.insert(1);
vm.settop(1);
}
private void loader_Java( LuaState vm ) {
String name = vm.tostring(2);
Class c = null;
LValue v = null;
try {
c = Class.forName(name);
v = (LValue) c.newInstance();
vm.pushlvalue( v );
} catch ( ClassNotFoundException cnfe ) {
vm.pushstring("\n\tno class '"+name+"'" );
} catch ( Exception e ) {
vm.pushstring("\n\tjava load failed on '"+name+"', "+e );
}
vm.insert(1);
vm.settop(1);
}
private InputStream findfile(LuaState vm, String name, LString pname) {
Platform p = Platform.getInstance();
LValue pkg = pckg.luaGetTable(vm, pckg, pname);
if ( ! pkg.isString() )
vm.error("package."+pname+" must be a string");
String path = pkg.toJavaString();
int e = -1;
int n = path.length();
StringBuffer sb = null;
name = name.replace('.','/');
while ( e < n ) {
// find next template
int b = e+1;
e = path.indexOf(';',b);
if ( e < 0 )
e = path.length();
String template = path.substring(b,e);
// create filename
int q = template.indexOf('?');
String filename = template;
if ( q >= 0 ) {
filename = template.substring(0,q) + name + template.substring(q+1);
}
// try opening the file
InputStream is = p.openFile(filename);
if ( is != null ) {
vm.pushstring(filename);
return is;
}
// report error
if ( sb == null )
sb = new StringBuffer();
sb.append( "\n\tno file '"+filename+"'");
}
// not found, push error on stack and return
vm.pushstring(sb.toString());
return null;
}
private static void loaderror(LuaState vm, String filename) {
vm.error( "error loading module '"+vm.tostring(1)+"' from file '"+filename+"':\n\t"+vm.tostring(-1) );
}
}
| false | true | public void require( LuaState vm ) {
LString name = vm.tolstring(2);
LValue loaded = LOADED.get(name);
if ( loaded.toJavaBoolean() ) {
if ( loaded == _SENTINEL )
vm.error("loop or previous error loading module '"+name+"'");
vm.resettop();
vm.pushlvalue( loaded );
return;
}
vm.resettop();
/* else must load it; iterate over available loaders */
LValue val = pckg.luaGetTable(vm, pckg, _LOADERS);
if ( ! val.isTable() )
vm.error( "'package.loaders' must be a table" );
vm.pushlvalue(val);
Vector v = new Vector();
for ( int i=1; true; i++ ) {
vm.rawgeti(1, i);
if ( vm.isnil(-1) ) {
vm.error( "module '"+name+"' not found: "+v );
}
/* call loader with module name as argument */
vm.pushlstring(name);
vm.call(1, 1);
if ( vm.isfunction(-1) )
break; /* module loaded successfully */
if ( vm.isstring(-1) ) /* loader returned error message? */
v.addElement(vm.tolstring(-1)); /* accumulate it */
vm.pop(1);
}
// load the module using the loader
LOADED.luaSetTable(vm, LOADED, name, _SENTINEL);
vm.pushlstring( name ); /* pass name as argument to module */
vm.call( 1, 1 ); /* run loaded module */
if ( ! vm.isnil(-1) ) /* non-nil return? */
LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */
if ( LOADED.luaGetTable(vm, LOADED, name) == _SENTINEL ) { /* module did not set a value? */
LOADED.luaSetTable(vm, LOADED, name, LBoolean.TRUE ); /* _LOADED[name] = true */
vm.pushboolean(true);
}
vm.replace(1);
vm.settop(1);
}
| public void require( LuaState vm ) {
LString name = vm.tolstring(2);
LValue loaded = LOADED.get(name);
if ( loaded.toJavaBoolean() ) {
if ( loaded == _SENTINEL )
vm.error("loop or previous error loading module '"+name+"'");
vm.resettop();
vm.pushlvalue( loaded );
return;
}
vm.resettop();
/* else must load it; iterate over available loaders */
LValue val = pckg.luaGetTable(vm, pckg, _LOADERS);
if ( ! val.isTable() )
vm.error( "'package.loaders' must be a table" );
vm.pushlvalue(val);
Vector v = new Vector();
for ( int i=1; true; i++ ) {
vm.rawgeti(1, i);
if ( vm.isnil(-1) ) {
vm.error( "module '"+name+"' not found: "+v );
}
/* call loader with module name as argument */
vm.pushlstring(name);
vm.call(1, 1);
if ( vm.isfunction(-1) )
break; /* module loaded successfully */
if ( vm.isstring(-1) ) /* loader returned error message? */
v.addElement(vm.tolstring(-1)); /* accumulate it */
vm.pop(1);
}
// load the module using the loader
LOADED.luaSetTable(vm, LOADED, name, _SENTINEL);
vm.pushlstring( name ); /* pass name as argument to module */
vm.call( 1, 1 ); /* run loaded module */
if ( ! vm.isnil(-1) ) /* non-nil return? */
LOADED.luaSetTable(vm, LOADED, name, vm.topointer(-1) ); /* _LOADED[name] = returned value */
LValue result = LOADED.luaGetTable(vm, LOADED, name);
if ( result == _SENTINEL ) { /* module did not set a value? */
LOADED.luaSetTable(vm, LOADED, name, result=LBoolean.TRUE ); /* _LOADED[name] = true */
}
vm.resettop();
vm.pushlvalue(result);
}
|
diff --git a/src/api/org/openmrs/validator/ConceptValidator.java b/src/api/org/openmrs/validator/ConceptValidator.java
index 01f76954..8ee9dde4 100644
--- a/src/api/org/openmrs/validator/ConceptValidator.java
+++ b/src/api/org/openmrs/validator/ConceptValidator.java
@@ -1,124 +1,124 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.validator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.annotation.Handler;
import org.openmrs.api.APIException;
import org.openmrs.api.DuplicateConceptNameException;
import org.openmrs.api.context.Context;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Validates methods of the {@link Concept} object.
*/
@Handler(supports = { Concept.class }, order = 50)
public class ConceptValidator implements Validator {
/** Log for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Determines if the command object being submitted is a valid type
*
* @see org.springframework.validation.Validator#supports(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public boolean supports(Class c) {
return c.equals(Concept.class);
}
/**
* Checks that a given concept object has a unique name or preferred name across the entire
* unretired and preferred concept name space in a given locale(should be the default
* application locale set in the openmrs context). Currently this method is called just before
* the concept is persisted in the database
*
* @should fail if there is a duplicate unretired concept name in the locale
* @should fail if the preferred name is an empty string
* @should fail if the object parameter is null
* @should pass if the found duplicate concept is actually retired
* @should pass if the concept is being updated with no name change
*/
public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
- if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
+ if (newConcept.getConceptId() != null && c.getConceptId().equals(newConcept.getConceptId()))
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
}
| true | true | public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
| public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId().equals(newConcept.getConceptId()))
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
|
diff --git a/src/uk/ac/horizon/ug/lobby/user/AddGameInstanceServlet.java b/src/uk/ac/horizon/ug/lobby/user/AddGameInstanceServlet.java
index 1881d1b..257950b 100755
--- a/src/uk/ac/horizon/ug/lobby/user/AddGameInstanceServlet.java
+++ b/src/uk/ac/horizon/ug/lobby/user/AddGameInstanceServlet.java
@@ -1,122 +1,122 @@
/**
* Copyright 2010 The University of Nottingham
*
* This file is part of lobbyservice.
*
* lobbyservice 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.
*
* lobbyservice is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with lobbyservice. If not, see <http://www.gnu.org/licenses/>.
*
*/
package uk.ac.horizon.ug.lobby.user;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.http.*;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.appengine.api.datastore.KeyFactory;
import uk.ac.horizon.ug.lobby.Constants;
import uk.ac.horizon.ug.lobby.RequestException;
import uk.ac.horizon.ug.lobby.model.Account;
import uk.ac.horizon.ug.lobby.model.EMF;
import uk.ac.horizon.ug.lobby.model.GameInstance;
import uk.ac.horizon.ug.lobby.model.GameServer;
import uk.ac.horizon.ug.lobby.model.GameServerStatus;
import uk.ac.horizon.ug.lobby.model.GameTemplate;
import uk.ac.horizon.ug.lobby.protocol.JSONUtils;
/**
* Get all Accounts (admin view).
*
* @author cmg
*
*/
@SuppressWarnings("serial")
public class AddGameInstanceServlet extends HttpServlet implements Constants {
static Logger logger = Logger.getLogger(AddGameInstanceServlet.class.getName());
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
GameInstance gi = null;
try {
BufferedReader r = req.getReader();
String line = r.readLine();
// why does this seem to read {} ??
//JSONObject json = new JSONObject(req.getReader());
JSONObject json = new JSONObject(line);
gi = JSONUtils.parseGameInstance(json);
}
catch (JSONException je) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, je.toString());
return;
}
Account account = null;
try {
account = AccountUtils.getAccount(req);
}catch (RequestException re) {
resp.sendError(re.getErrorCode(), re.getMessage());
return;
}
EntityManager em = EMF.get().createEntityManager();
GameServer gs = null;
GameTemplate gt = null;
try {
// not sure when to enforce this...
if (gi.getGameServerId()!=null) {
gs = em.find(GameServer.class, gi.getGameServerId());
if (gs==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameServer '"+gi.getGameServerId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gs.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameServer '"+gi.getGameServerId()+"' not owned by "+account.getNickname());
return;
}
}
if (gi.getGameTemplateId()==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance must have gameTemplateId");
return;
}
gt = em.find(GameTemplate.class, GameTemplate.idToKey(gi.getGameTemplateId()));
if (gt==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gt.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' not owned by "+account.getNickname());
return;
}
// cache state
- if (gi.getNumSlotsAllocated()<=0)
+ if (gi.getMaxNumSlots()<=0)
gi.setFull(true);
em.persist(gi);
logger.info("Creating GameInstance "+gi+" for Account "+account.getUserId()+" ("+account.getNickname()+")");
}
finally {
em.close();
}
JSONUtils.sendGameInstance(resp, gi, gt, gs);
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
GameInstance gi = null;
try {
BufferedReader r = req.getReader();
String line = r.readLine();
// why does this seem to read {} ??
//JSONObject json = new JSONObject(req.getReader());
JSONObject json = new JSONObject(line);
gi = JSONUtils.parseGameInstance(json);
}
catch (JSONException je) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, je.toString());
return;
}
Account account = null;
try {
account = AccountUtils.getAccount(req);
}catch (RequestException re) {
resp.sendError(re.getErrorCode(), re.getMessage());
return;
}
EntityManager em = EMF.get().createEntityManager();
GameServer gs = null;
GameTemplate gt = null;
try {
// not sure when to enforce this...
if (gi.getGameServerId()!=null) {
gs = em.find(GameServer.class, gi.getGameServerId());
if (gs==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameServer '"+gi.getGameServerId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gs.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameServer '"+gi.getGameServerId()+"' not owned by "+account.getNickname());
return;
}
}
if (gi.getGameTemplateId()==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance must have gameTemplateId");
return;
}
gt = em.find(GameTemplate.class, GameTemplate.idToKey(gi.getGameTemplateId()));
if (gt==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gt.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' not owned by "+account.getNickname());
return;
}
// cache state
if (gi.getNumSlotsAllocated()<=0)
gi.setFull(true);
em.persist(gi);
logger.info("Creating GameInstance "+gi+" for Account "+account.getUserId()+" ("+account.getNickname()+")");
}
finally {
em.close();
}
JSONUtils.sendGameInstance(resp, gi, gt, gs);
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
GameInstance gi = null;
try {
BufferedReader r = req.getReader();
String line = r.readLine();
// why does this seem to read {} ??
//JSONObject json = new JSONObject(req.getReader());
JSONObject json = new JSONObject(line);
gi = JSONUtils.parseGameInstance(json);
}
catch (JSONException je) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, je.toString());
return;
}
Account account = null;
try {
account = AccountUtils.getAccount(req);
}catch (RequestException re) {
resp.sendError(re.getErrorCode(), re.getMessage());
return;
}
EntityManager em = EMF.get().createEntityManager();
GameServer gs = null;
GameTemplate gt = null;
try {
// not sure when to enforce this...
if (gi.getGameServerId()!=null) {
gs = em.find(GameServer.class, gi.getGameServerId());
if (gs==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameServer '"+gi.getGameServerId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gs.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameServer '"+gi.getGameServerId()+"' not owned by "+account.getNickname());
return;
}
}
if (gi.getGameTemplateId()==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance must have gameTemplateId");
return;
}
gt = em.find(GameTemplate.class, GameTemplate.idToKey(gi.getGameTemplateId()));
if (gt==null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' unknown");
return;
}
if (!KeyFactory.keyToString(gt.getOwnerId()).equals(KeyFactory.keyToString(account.getKey()))) {
resp.sendError(HttpServletResponse.SC_FORBIDDEN,"Add GameInstance GameTemplate '"+gi.getGameTemplateId()+"' not owned by "+account.getNickname());
return;
}
// cache state
if (gi.getMaxNumSlots()<=0)
gi.setFull(true);
em.persist(gi);
logger.info("Creating GameInstance "+gi+" for Account "+account.getUserId()+" ("+account.getNickname()+")");
}
finally {
em.close();
}
JSONUtils.sendGameInstance(resp, gi, gt, gs);
}
|
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncHttpConnection.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncHttpConnection.java
index 97b66d058..84557ca79 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncHttpConnection.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AsyncHttpConnection.java
@@ -1,153 +1,153 @@
package org.eclipse.jetty.server;
import java.io.IOException;
import org.eclipse.jetty.http.HttpException;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.io.AsyncEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.nio.SelectChannelEndPoint;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
public class AsyncHttpConnection extends HttpConnection
{
private final static int NO_PROGRESS_INFO = Integer.getInteger("org.mortbay.jetty.NO_PROGRESS_INFO",100);
private final static int NO_PROGRESS_CLOSE = Integer.getInteger("org.mortbay.jetty.NO_PROGRESS_CLOSE",1000);
private static final Logger LOG = Log.getLogger(AsyncHttpConnection.class);
private int _total_no_progress;
public AsyncHttpConnection(Connector connector, EndPoint endpoint, Server server)
{
super(connector,endpoint,server);
}
public Connection handle() throws IOException
{
LOG.debug("handle {}",this);
Connection connection = this;
boolean some_progress=false;
boolean progress=true;
// Loop while more in buffer
try
{
setCurrentConnection(this);
boolean more_in_buffer =false;
- while (_endp.isOpen() && (more_in_buffer || progress))
+ while (_endp.isOpen() && (more_in_buffer || progress) && connection==this)
{
progress=false;
try
{
// Handle resumed request
if (_request._async.isAsync() && !_request._async.isComplete())
handleRequest();
// else Parse more input
else if (!_parser.isComplete() && _parser.parseAvailable()>0)
progress=true;
// Generate more output
if (_generator.isCommitted() && !_generator.isComplete() && _generator.flushBuffer()>0)
progress=true;
// Flush output from buffering endpoint
if (_endp.isBufferingOutput())
_endp.flush();
}
catch (HttpException e)
{
if (LOG.isDebugEnabled())
{
LOG.debug("uri="+_uri);
LOG.debug("fields="+_requestFields);
LOG.debug(e);
}
_generator.sendError(e.getStatus(), e.getReason(), null, true);
_parser.reset();
_endp.close();
}
finally
{
// Do we need to complete a half close?
if (_endp.isInputShutdown() && (_parser.isIdle() || _parser.isComplete()))
{
LOG.debug("complete half close {}",this);
more_in_buffer=false;
_endp.close();
reset(true);
}
// else Is this request/response round complete?
else if (_parser.isComplete() && _generator.isComplete() && !_endp.isBufferingOutput())
{
// look for a switched connection instance?
if (_response.getStatus()==HttpStatus.SWITCHING_PROTOCOLS_101)
{
Connection switched=(Connection)_request.getAttribute("org.eclipse.jetty.io.Connection");
if (switched!=null)
{
_parser.reset();
_generator.reset(true);
- return switched;
+ connection=switched;
}
}
// Reset the parser/generator
// keep the buffers as we will cycle
progress=true;
reset(false);
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
}
// else Are we suspended?
else if (_request.isAsyncStarted())
{
LOG.debug("suspended {}",this);
more_in_buffer=false;
progress=false;
}
else
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
some_progress|=progress|((SelectChannelEndPoint)_endp).isProgressing();
}
}
}
finally
{
setCurrentConnection(null);
_parser.returnBuffers();
// Are we write blocked
if (_generator.isCommitted() && !_generator.isComplete() && _endp.isOpen())
((AsyncEndPoint)_endp).scheduleWrite();
else
_generator.returnBuffers();
if (!some_progress)
{
_total_no_progress++;
if (NO_PROGRESS_INFO>0 && _total_no_progress%NO_PROGRESS_INFO==0 && (NO_PROGRESS_CLOSE<=0 || _total_no_progress< NO_PROGRESS_CLOSE))
LOG.info("EndPoint making no progress: "+_total_no_progress+" "+_endp);
if (NO_PROGRESS_CLOSE>0 && _total_no_progress>NO_PROGRESS_CLOSE)
{
LOG.warn("Closing EndPoint making no progress: "+_total_no_progress+" "+_endp);
_endp.close();
if (_endp instanceof SelectChannelEndPoint)
{
System.err.println(((SelectChannelEndPoint)_endp).getSelectManager().dump());
}
}
}
LOG.debug("unhandle {}",this);
}
return connection;
}
}
| false | true | public Connection handle() throws IOException
{
LOG.debug("handle {}",this);
Connection connection = this;
boolean some_progress=false;
boolean progress=true;
// Loop while more in buffer
try
{
setCurrentConnection(this);
boolean more_in_buffer =false;
while (_endp.isOpen() && (more_in_buffer || progress))
{
progress=false;
try
{
// Handle resumed request
if (_request._async.isAsync() && !_request._async.isComplete())
handleRequest();
// else Parse more input
else if (!_parser.isComplete() && _parser.parseAvailable()>0)
progress=true;
// Generate more output
if (_generator.isCommitted() && !_generator.isComplete() && _generator.flushBuffer()>0)
progress=true;
// Flush output from buffering endpoint
if (_endp.isBufferingOutput())
_endp.flush();
}
catch (HttpException e)
{
if (LOG.isDebugEnabled())
{
LOG.debug("uri="+_uri);
LOG.debug("fields="+_requestFields);
LOG.debug(e);
}
_generator.sendError(e.getStatus(), e.getReason(), null, true);
_parser.reset();
_endp.close();
}
finally
{
// Do we need to complete a half close?
if (_endp.isInputShutdown() && (_parser.isIdle() || _parser.isComplete()))
{
LOG.debug("complete half close {}",this);
more_in_buffer=false;
_endp.close();
reset(true);
}
// else Is this request/response round complete?
else if (_parser.isComplete() && _generator.isComplete() && !_endp.isBufferingOutput())
{
// look for a switched connection instance?
if (_response.getStatus()==HttpStatus.SWITCHING_PROTOCOLS_101)
{
Connection switched=(Connection)_request.getAttribute("org.eclipse.jetty.io.Connection");
if (switched!=null)
{
_parser.reset();
_generator.reset(true);
return switched;
}
}
// Reset the parser/generator
// keep the buffers as we will cycle
progress=true;
reset(false);
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
}
// else Are we suspended?
else if (_request.isAsyncStarted())
{
LOG.debug("suspended {}",this);
more_in_buffer=false;
progress=false;
}
else
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
some_progress|=progress|((SelectChannelEndPoint)_endp).isProgressing();
}
}
}
finally
{
setCurrentConnection(null);
_parser.returnBuffers();
// Are we write blocked
if (_generator.isCommitted() && !_generator.isComplete() && _endp.isOpen())
((AsyncEndPoint)_endp).scheduleWrite();
else
_generator.returnBuffers();
if (!some_progress)
{
_total_no_progress++;
if (NO_PROGRESS_INFO>0 && _total_no_progress%NO_PROGRESS_INFO==0 && (NO_PROGRESS_CLOSE<=0 || _total_no_progress< NO_PROGRESS_CLOSE))
LOG.info("EndPoint making no progress: "+_total_no_progress+" "+_endp);
if (NO_PROGRESS_CLOSE>0 && _total_no_progress>NO_PROGRESS_CLOSE)
{
LOG.warn("Closing EndPoint making no progress: "+_total_no_progress+" "+_endp);
_endp.close();
if (_endp instanceof SelectChannelEndPoint)
{
System.err.println(((SelectChannelEndPoint)_endp).getSelectManager().dump());
}
}
}
LOG.debug("unhandle {}",this);
}
return connection;
}
| public Connection handle() throws IOException
{
LOG.debug("handle {}",this);
Connection connection = this;
boolean some_progress=false;
boolean progress=true;
// Loop while more in buffer
try
{
setCurrentConnection(this);
boolean more_in_buffer =false;
while (_endp.isOpen() && (more_in_buffer || progress) && connection==this)
{
progress=false;
try
{
// Handle resumed request
if (_request._async.isAsync() && !_request._async.isComplete())
handleRequest();
// else Parse more input
else if (!_parser.isComplete() && _parser.parseAvailable()>0)
progress=true;
// Generate more output
if (_generator.isCommitted() && !_generator.isComplete() && _generator.flushBuffer()>0)
progress=true;
// Flush output from buffering endpoint
if (_endp.isBufferingOutput())
_endp.flush();
}
catch (HttpException e)
{
if (LOG.isDebugEnabled())
{
LOG.debug("uri="+_uri);
LOG.debug("fields="+_requestFields);
LOG.debug(e);
}
_generator.sendError(e.getStatus(), e.getReason(), null, true);
_parser.reset();
_endp.close();
}
finally
{
// Do we need to complete a half close?
if (_endp.isInputShutdown() && (_parser.isIdle() || _parser.isComplete()))
{
LOG.debug("complete half close {}",this);
more_in_buffer=false;
_endp.close();
reset(true);
}
// else Is this request/response round complete?
else if (_parser.isComplete() && _generator.isComplete() && !_endp.isBufferingOutput())
{
// look for a switched connection instance?
if (_response.getStatus()==HttpStatus.SWITCHING_PROTOCOLS_101)
{
Connection switched=(Connection)_request.getAttribute("org.eclipse.jetty.io.Connection");
if (switched!=null)
{
_parser.reset();
_generator.reset(true);
connection=switched;
}
}
// Reset the parser/generator
// keep the buffers as we will cycle
progress=true;
reset(false);
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
}
// else Are we suspended?
else if (_request.isAsyncStarted())
{
LOG.debug("suspended {}",this);
more_in_buffer=false;
progress=false;
}
else
more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
some_progress|=progress|((SelectChannelEndPoint)_endp).isProgressing();
}
}
}
finally
{
setCurrentConnection(null);
_parser.returnBuffers();
// Are we write blocked
if (_generator.isCommitted() && !_generator.isComplete() && _endp.isOpen())
((AsyncEndPoint)_endp).scheduleWrite();
else
_generator.returnBuffers();
if (!some_progress)
{
_total_no_progress++;
if (NO_PROGRESS_INFO>0 && _total_no_progress%NO_PROGRESS_INFO==0 && (NO_PROGRESS_CLOSE<=0 || _total_no_progress< NO_PROGRESS_CLOSE))
LOG.info("EndPoint making no progress: "+_total_no_progress+" "+_endp);
if (NO_PROGRESS_CLOSE>0 && _total_no_progress>NO_PROGRESS_CLOSE)
{
LOG.warn("Closing EndPoint making no progress: "+_total_no_progress+" "+_endp);
_endp.close();
if (_endp instanceof SelectChannelEndPoint)
{
System.err.println(((SelectChannelEndPoint)_endp).getSelectManager().dump());
}
}
}
LOG.debug("unhandle {}",this);
}
return connection;
}
|
diff --git a/sdk/jme3-core/src/com/jme3/gde/core/scene/processors/WireProcessor.java b/sdk/jme3-core/src/com/jme3/gde/core/scene/processors/WireProcessor.java
index d137954a7..75a307f5f 100644
--- a/sdk/jme3-core/src/com/jme3/gde/core/scene/processors/WireProcessor.java
+++ b/sdk/jme3-core/src/com/jme3/gde/core/scene/processors/WireProcessor.java
@@ -1,83 +1,84 @@
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.gde.core.scene.processors;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.post.SceneProcessor;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.texture.FrameBuffer;
/**
*
* @author tomas
*/
public class WireProcessor implements SceneProcessor {
RenderManager renderManager;
Material wireMaterial;
public WireProcessor(AssetManager manager) {
- wireMaterial = new Material(manager, "/Common/MatDefs/Misc/WireColor.j3md");
+ wireMaterial = new Material(manager, "/Common/MatDefs/Misc/Unshaded.j3md");
+ wireMaterial.getAdditionalRenderState().setWireframe(true);
wireMaterial.setColor("Color", ColorRGBA.Blue);
}
public void initialize(RenderManager rm, ViewPort vp) {
renderManager = rm;
}
public void reshape(ViewPort vp, int w, int h) {
// do nothing
}
public boolean isInitialized() {
return renderManager != null;
}
public void preFrame(float tpf) {
}
public void postQueue(RenderQueue rq) {
renderManager.setForcedMaterial(wireMaterial);
}
public void postFrame(FrameBuffer out) {
renderManager.setForcedMaterial(null);
}
public void cleanup() {
renderManager.setForcedMaterial(null);
}
}
| true | true | public WireProcessor(AssetManager manager) {
wireMaterial = new Material(manager, "/Common/MatDefs/Misc/WireColor.j3md");
wireMaterial.setColor("Color", ColorRGBA.Blue);
}
| public WireProcessor(AssetManager manager) {
wireMaterial = new Material(manager, "/Common/MatDefs/Misc/Unshaded.j3md");
wireMaterial.getAdditionalRenderState().setWireframe(true);
wireMaterial.setColor("Color", ColorRGBA.Blue);
}
|
diff --git a/drools-core/src/test/java/org/drools/process/TimerTest.java b/drools-core/src/test/java/org/drools/process/TimerTest.java
index 60d9eeca3..0eacd6568 100644
--- a/drools-core/src/test/java/org/drools/process/TimerTest.java
+++ b/drools-core/src/test/java/org/drools/process/TimerTest.java
@@ -1,81 +1,84 @@
package org.drools.process;
import junit.framework.TestCase;
import org.drools.RuleBaseFactory;
import org.drools.common.AbstractRuleBase;
import org.drools.common.InternalWorkingMemory;
import org.drools.process.core.timer.Timer;
import org.drools.process.instance.timer.TimerManager;
import org.drools.reteoo.ReteooWorkingMemory;
import org.drools.ruleflow.instance.RuleFlowProcessInstance;
public class TimerTest extends TestCase {
private int counter = 0;
public void testTimer() {
AbstractRuleBase ruleBase = (AbstractRuleBase) RuleBaseFactory.newRuleBase();
InternalWorkingMemory workingMemory = new ReteooWorkingMemory(1, ruleBase);
RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance() {
- public void timerTriggered(Timer timer) {
- System.out.println("Timer " + timer.getId() + " triggered");
- counter++;
+ public void signalEvent(String type, Object event) {
+ if ("timerTriggered".equals(type)) {
+ Timer timer = (Timer) event;
+ System.out.println("Timer " + timer.getId() + " triggered");
+ counter++;
+ }
}
};
processInstance.setId(1234);
workingMemory.addProcessInstance(processInstance);
TimerManager timerManager = workingMemory.getTimerManager();
Timer timer = new Timer();
timerManager.registerTimer(timer, processInstance);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timer.setPeriod(300);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
// we can't know exactly how many times this will fire as timers are not precise, but should be atleast 4
assertTrue( counter >= 4 );
timerManager.cancelTimer(timer);
int lastCount = counter;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(lastCount, counter);
}
}
| true | true | public void testTimer() {
AbstractRuleBase ruleBase = (AbstractRuleBase) RuleBaseFactory.newRuleBase();
InternalWorkingMemory workingMemory = new ReteooWorkingMemory(1, ruleBase);
RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance() {
public void timerTriggered(Timer timer) {
System.out.println("Timer " + timer.getId() + " triggered");
counter++;
}
};
processInstance.setId(1234);
workingMemory.addProcessInstance(processInstance);
TimerManager timerManager = workingMemory.getTimerManager();
Timer timer = new Timer();
timerManager.registerTimer(timer, processInstance);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timer.setPeriod(300);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
// we can't know exactly how many times this will fire as timers are not precise, but should be atleast 4
assertTrue( counter >= 4 );
timerManager.cancelTimer(timer);
int lastCount = counter;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(lastCount, counter);
}
| public void testTimer() {
AbstractRuleBase ruleBase = (AbstractRuleBase) RuleBaseFactory.newRuleBase();
InternalWorkingMemory workingMemory = new ReteooWorkingMemory(1, ruleBase);
RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance() {
public void signalEvent(String type, Object event) {
if ("timerTriggered".equals(type)) {
Timer timer = (Timer) event;
System.out.println("Timer " + timer.getId() + " triggered");
counter++;
}
}
};
processInstance.setId(1234);
workingMemory.addProcessInstance(processInstance);
TimerManager timerManager = workingMemory.getTimerManager();
Timer timer = new Timer();
timerManager.registerTimer(timer, processInstance);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
counter = 0;
timer = new Timer();
timer.setDelay(500);
timer.setPeriod(300);
timerManager.registerTimer(timer, processInstance);
assertEquals(0, counter);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(1, counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
// we can't know exactly how many times this will fire as timers are not precise, but should be atleast 4
assertTrue( counter >= 4 );
timerManager.cancelTimer(timer);
int lastCount = counter;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// do nothing
}
assertEquals(lastCount, counter);
}
|
diff --git a/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java b/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
index fc32ff02..df415d32 100644
--- a/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
+++ b/web/src/main/java/org/openmrs/web/dwr/DWRPatientService.java
@@ -1,802 +1,805 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.dwr;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.GlobalProperty;
import org.openmrs.Location;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.PersonAddress;
import org.openmrs.activelist.Allergy;
import org.openmrs.activelist.AllergySeverity;
import org.openmrs.activelist.AllergyType;
import org.openmrs.activelist.Problem;
import org.openmrs.activelist.ProblemModifier;
import org.openmrs.api.APIAuthenticationException;
import org.openmrs.api.APIException;
import org.openmrs.api.ConceptService;
import org.openmrs.api.DuplicateIdentifierException;
import org.openmrs.api.GlobalPropertyListener;
import org.openmrs.api.IdentifierNotUniqueException;
import org.openmrs.api.InsufficientIdentifiersException;
import org.openmrs.api.InvalidCheckDigitException;
import org.openmrs.api.InvalidIdentifierFormatException;
import org.openmrs.api.LocationService;
import org.openmrs.api.PatientIdentifierException;
import org.openmrs.api.PatientService;
import org.openmrs.api.context.Context;
import org.openmrs.patient.IdentifierValidator;
import org.openmrs.patient.UnallowedIdentifierException;
import org.openmrs.util.OpenmrsConstants;
/**
* DWR patient methods. The methods in here are used in the webapp to get data from the database via
* javascript calls.
*
* @see PatientService
*/
public class DWRPatientService implements GlobalPropertyListener {
private static final Log log = LogFactory.getLog(DWRPatientService.class);
private static Integer maximumResults;
/**
* Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
* search. Else, do a name search
*
* @param searchValue string to be looked for
* @param includeVoided true/false whether or not to included voided patients
* @return Collection<Object> of PatientListItem or String
* @should return only patient list items with nonnumeric search
* @should return string warning if invalid patient identifier
* @should not return string warning if searching with valid identifier
* @should include string in results if doing extra decapitated search
* @should not return duplicate patient list items if doing decapitated search
* @should not do decapitated search if numbers are in the search string
* @should get results for patients that have edited themselves
* @should logged in user should load their own patient object
*/
public Collection<Object> findPatients(String searchValue, boolean includeVoided) {
return findBatchOfPatients(searchValue, includeVoided, null, null);
}
/**
* Search on the <code>searchValue</code>. If a number is in the search string, do an identifier
* search. Else, do a name search
*
* @see PatientService#getPatients(String, String, List, boolean, int, Integer)
* @param searchValue string to be looked for
* @param includeVoided true/false whether or not to included voided patients
* @param start The starting index for the results to return
* @param length The number of results of return
* @return Collection<Object> of PatientListItem or String
* @since 1.8
*/
@SuppressWarnings("unchecked")
public Collection<Object> findBatchOfPatients(String searchValue, boolean includeVoided, Integer start, Integer length) {
if (maximumResults == null)
maximumResults = getMaximumSearchResults();
if (length != null && length > maximumResults)
length = maximumResults;
// the list to return
List<Object> patientList = new Vector<Object>();
PatientService ps = Context.getPatientService();
Collection<Patient> patients;
try {
patients = ps.getPatients(searchValue, start, length);
}
catch (APIAuthenticationException e) {
patientList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
return patientList;
}
patientList = new Vector<Object>(patients.size());
for (Patient p : patients)
patientList.add(new PatientListItem(p));
// if the length wasn't limited to less than 3 or this is the second ajax call
// and only 2 results found and a number was not in the
// search, then do a decapitated search: trim each word
// down to the first three characters and search again
if ((length == null || length > 2) && patients.size() < 3 && !searchValue.matches(".*\\d+.*")) {
String[] names = searchValue.split(" ");
String newSearch = "";
for (String name : names) {
if (name.length() > 3)
name = name.substring(0, 4);
newSearch += " " + name;
}
newSearch = newSearch.trim();
if (!newSearch.equals(searchValue)) {
Collection<Patient> newPatients = ps.getPatients(newSearch, start, length);
patients = CollectionUtils.union(newPatients, patients); // get unique hits
//reconstruct the results list
if (newPatients.size() > 0) {
patientList = new Vector<Object>(patients.size());
//patientList.add("Minimal patients returned. Results for <b>" + newSearch + "</b>");
for (Patient p : newPatients) {
PatientListItem pi = new PatientListItem(p);
patientList.add(pi);
}
}
}
}
//no results found and a number was in the search --
//should check whether the check digit is correct.
else if (patients.size() == 0 && searchValue.matches(".*\\d+.*")) {
//Looks through all the patient identifier validators to see if this type of identifier
//is supported for any of them. If it isn't, then no need to warn about a bad check
//digit. If it does match, then if any of the validators validates the check digit
//successfully, then the user is notified that the identifier has been entered correctly.
//Otherwise, the user is notified that the identifier was entered incorrectly.
Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
boolean shouldWarnUser = true;
boolean validCheckDigit = false;
boolean identifierMatchesValidationScheme = false;
for (IdentifierValidator piv : pivs) {
try {
if (piv.isValid(searchValue)) {
shouldWarnUser = false;
validCheckDigit = true;
}
identifierMatchesValidationScheme = true;
}
catch (UnallowedIdentifierException e) {}
}
if (identifierMatchesValidationScheme) {
if (shouldWarnUser)
patientList
.add("<p style=\"color:red; font-size:big;\"><b>WARNING: Identifier has been typed incorrectly! Please double check the identifier.</b></p>");
else if (validCheckDigit)
patientList
.add("<p style=\"color:green; font-size:big;\"><b>This identifier has been entered correctly, but still no patients have been found.</b></p>");
}
}
return patientList;
}
/**
* Returns a map of results with the values as count of matches and a partial list of the
* matching patients (depending on values of start and length parameters) while the keys are are
* 'count' and 'objectList' respectively, if the length parameter is not specified, then all
* matches will be returned from the start index if specified.
*
* @param searchValue patient name or identifier
* @param start the beginning index
* @param length the number of matching patients to return
* @param getMatchCount Specifies if the count of matches should be included in the returned map
* @return a map of results
* @throws APIException
* @since 1.8
*/
@SuppressWarnings("unchecked")
public Map<String, Object> findCountAndPatients(String searchValue, Integer start, Integer length, boolean getMatchCount)
throws APIException {
//Map to return
Map<String, Object> resultsMap = new HashMap<String, Object>();
Collection<Object> objectList = new Vector<Object>();
try {
PatientService ps = Context.getPatientService();
int patientCount = 0;
//if this is the first call
if (getMatchCount) {
patientCount += ps.getCountOfPatients(searchValue);
// if only 2 results found and a number was not in the
// search, then do a decapitated search: trim each word
// down to the first three characters and search again
if ((length == null || length > 2) && patientCount < 3 && !searchValue.matches(".*\\d+.*")) {
String[] names = searchValue.split(" ");
String newSearch = "";
for (String name : names) {
if (name.length() > 3)
name = name.substring(0, 4);
newSearch += " " + name;
}
newSearch = newSearch.trim();
if (!newSearch.equals(searchValue)) {
//since we already know that the list is small, it doesn't hurt to load the hits
//so that we can remove them from the list of the new search results and get the
//accurate count of matches
Collection<Patient> patients = ps.getPatients(searchValue);
newSearch = newSearch.trim();
Collection<Patient> newPatients = ps.getPatients(newSearch);
newPatients = CollectionUtils.union(newPatients, patients);
//Re-compute the count of all the unique patient hits
patientCount = newPatients.size();
if (newPatients.size() > 0) {
resultsMap.put("notification", Context.getMessageSourceService().getMessage(
"Patient.warning.minimalSearchResults", new Object[] { newSearch }, Context.getLocale()));
}
}
}
//no results found and a number was in the search --
//should check whether the check digit is correct.
else if (patientCount == 0 && searchValue.matches(".*\\d+.*")) {
//Looks through all the patient identifier validators to see if this type of identifier
//is supported for any of them. If it isn't, then no need to warn about a bad check
//digit. If it does match, then if any of the validators validates the check digit
//successfully, then the user is notified that the identifier has been entered correctly.
//Otherwise, the user is notified that the identifier was entered incorrectly.
Collection<IdentifierValidator> pivs = ps.getAllIdentifierValidators();
boolean shouldWarnUser = true;
boolean validCheckDigit = false;
boolean identifierMatchesValidationScheme = false;
for (IdentifierValidator piv : pivs) {
try {
if (piv.isValid(searchValue)) {
shouldWarnUser = false;
validCheckDigit = true;
}
identifierMatchesValidationScheme = true;
}
catch (UnallowedIdentifierException e) {}
}
if (identifierMatchesValidationScheme) {
if (shouldWarnUser)
resultsMap.put("notification", "<b>"
+ Context.getMessageSourceService().getMessage("Patient.warning.inValidIdentifier")
+ "<b/>");
else if (validCheckDigit)
resultsMap.put("notification", "<b style=\"color:green;\">"
+ Context.getMessageSourceService().getMessage("Patient.message.validIdentifier")
+ "<b/>");
}
} else {
//ensure that count never exceeds this value because the API's service layer would never
//return more than it since it is limited in the DAO layer
if (maximumResults == null)
maximumResults = getMaximumSearchResults();
if (length != null && length > maximumResults)
length = maximumResults;
if (patientCount > maximumResults) {
patientCount = maximumResults;
if (log.isDebugEnabled())
log.debug("Limitng the size of matching patients to " + maximumResults);
}
}
}
//if we have any matches or this isn't the first ajax call when the caller
//requests for the count
if (patientCount > 0 || !getMatchCount)
objectList = findBatchOfPatients(searchValue, false, start, length);
resultsMap.put("count", patientCount);
resultsMap.put("objectList", objectList);
}
catch (Exception e) {
log.error("Error while searching for patients", e);
objectList.clear();
objectList.add(Context.getMessageSourceService().getMessage("Patient.search.error") + " - " + e.getMessage());
resultsMap.put("count", 0);
resultsMap.put("objectList", objectList);
}
return resultsMap;
}
/**
* Convenience method for dwr/javascript to convert a patient id into a Patient object (or at
* least into data about the patient)
*
* @param patientId the {@link Patient#getPatientId()} to match on
* @return a truncated Patient object in the form of a PatientListItem
*/
public PatientListItem getPatient(Integer patientId) {
PatientService ps = Context.getPatientService();
Patient p = ps.getPatient(patientId);
PatientListItem pli = new PatientListItem(p);
if (p != null && p.getAddresses() != null && p.getAddresses().size() > 0) {
PersonAddress pa = (PersonAddress) p.getAddresses().toArray()[0];
pli.setAddress1(pa.getAddress1());
pli.setAddress2(pa.getAddress2());
}
return pli;
}
/**
* find all patients with duplicate attributes (searchOn)
*
* @param searchOn
* @return list of patientListItems
*/
public Vector<Object> findDuplicatePatients(String[] searchOn) {
Vector<Object> patientList = new Vector<Object>();
try {
List<String> options = new Vector<String>(searchOn.length);
for (String s : searchOn)
options.add(s);
List<Patient> patients = Context.getPatientService().getDuplicatePatientsByAttributes(options);
if (patients.size() > 200)
patients.subList(0, 200);
for (Patient p : patients)
patientList.add(new PatientListItem(p));
}
catch (Exception e) {
log.error(e);
patientList.add("Error while attempting to find duplicate patients - " + e.getMessage());
}
return patientList;
}
/**
* Auto generated method comment
*
* @param patientId
* @param identifierType
* @param identifier
* @param identifierLocationId
* @return
*/
public String addIdentifier(Integer patientId, String identifierType, String identifier, Integer identifierLocationId) {
String ret = "";
if (identifier == null || identifier.length() == 0)
return "PatientIdentifier.error.general";
PatientService ps = Context.getPatientService();
LocationService ls = Context.getLocationService();
Patient p = ps.getPatient(patientId);
PatientIdentifierType idType = ps.getPatientIdentifierTypeByName(identifierType);
//ps.updatePatientIdentifier(pi);
Location location = ls.getLocation(identifierLocationId);
log.debug("idType=" + identifierType + "->" + idType + " , location=" + identifierLocationId + "->" + location
+ " identifier=" + identifier);
PatientIdentifier id = new PatientIdentifier();
id.setIdentifierType(idType);
id.setIdentifier(identifier);
id.setLocation(location);
// in case we are editing, check to see if there is already an ID of this type and location
for (PatientIdentifier previousId : p.getActiveIdentifiers()) {
if (previousId.getIdentifierType().equals(idType) && previousId.getLocation().equals(location)) {
log.debug("Found equivalent ID: [" + idType + "][" + location + "][" + previousId.getIdentifier()
+ "], about to remove");
p.removeIdentifier(previousId);
} else {
if (!previousId.getIdentifierType().equals(idType))
log.debug("Previous ID id type does not match: [" + previousId.getIdentifierType().getName() + "]["
+ previousId.getIdentifier() + "]");
if (!previousId.getLocation().equals(location)) {
log.debug("Previous ID location is: " + previousId.getLocation());
log.debug("New location is: " + location);
}
}
}
p.addIdentifier(id);
try {
ps.savePatient(p);
}
catch (InvalidIdentifierFormatException iife) {
log.error(iife);
ret = "PatientIdentifier.error.formatInvalid";
}
catch (InvalidCheckDigitException icde) {
log.error(icde);
ret = "PatientIdentifier.error.checkDigit";
}
catch (IdentifierNotUniqueException inue) {
log.error(inue);
ret = "PatientIdentifier.error.notUnique";
}
catch (DuplicateIdentifierException die) {
log.error(die);
ret = "PatientIdentifier.error.duplicate";
}
catch (InsufficientIdentifiersException iie) {
log.error(iie);
ret = "PatientIdentifier.error.insufficientIdentifiers";
}
catch (PatientIdentifierException pie) {
log.error(pie);
ret = "PatientIdentifier.error.general";
}
return ret;
}
/**
* Auto generated method comment
*
* @param patientId
* @param reasonForExitId
* @param dateOfExit
* @param causeOfDeath
* @param otherReason
* @return
*/
public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
log.warn("Caught error", e);
- ret = "Internal error while trying to process patient death - unable to proceed. Cause: " + e.getMessage();
+ ret = "Internal error while trying to process patient death - unable to proceed. Cause: "
+ + e.getMessage();
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
- ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
+ ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
+ + e.getMessage();
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
- ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
+ ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
+ + e.getMessage();
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
/**
* Auto generated method comment
*
* @param patientId
* @param locationId
* @return
*/
public String changeHealthCenter(Integer patientId, Integer locationId) {
log.warn("Deprecated method in 'DWRPatientService.changeHealthCenter'");
String ret = "";
/*
if ( patientId != null && locationId != null ) {
Patient patient = Context.getPatientService().getPatient(patientId);
Location location = Context.getEncounterService().getLocation(locationId);
if ( patient != null && location != null ) {
patient.setHealthCenter(location);
Context.getPatientService().updatePatient(patient);
}
}
*/
return ret;
}
/**
* Creates an Allergy Item
*
* @param patientId
* @param allergenId
* @param type
* @param pStartDate
* @param severity
* @param reactionId
*/
public void createAllergy(Integer patientId, Integer allergenId, String type, String pStartDate, String severity,
Integer reactionId) {
Date startDate = parseDate(pStartDate);
Patient patient = Context.getPatientService().getPatient(patientId);
Concept allergyConcept = Context.getConceptService().getConcept(allergenId);
Concept reactionConcept = (reactionId == null) ? null : Context.getConceptService().getConcept(reactionId);
AllergySeverity allergySeverity = StringUtils.isBlank(severity) ? null : AllergySeverity.valueOf(severity);
AllergyType allergyType = StringUtils.isBlank(type) ? null : AllergyType.valueOf(type);
Allergy allergy = new Allergy(patient, allergyConcept, startDate, allergyType, reactionConcept, allergySeverity);
Context.getPatientService().saveAllergy(allergy);
}
/**
* Save an Allergy
*
* @param activeListItemId
* @param allergenId Concept ID
* @param type
* @param pStartDate
* @param severity
* @param reactionId
*/
public void saveAllergy(Integer activeListItemId, Integer allergenId, String type, String pStartDate, String severity,
Integer reactionId) {
//get the allergy
Allergy allergy = Context.getPatientService().getAllergy(activeListItemId);
allergy.setAllergen(Context.getConceptService().getConcept(allergenId));
allergy.setAllergyType(type);
allergy.setStartDate(parseDate(pStartDate));
allergy.setSeverity(severity);
allergy.setReaction((reactionId == null) ? null : Context.getConceptService().getConcept(reactionId));
Context.getPatientService().saveAllergy(allergy);
}
/**
* Resolve an allergy
*
* @param activeListId
* @param resolved
* @param reason
* @param pEndDate
*/
public void removeAllergy(Integer activeListId, String reason) {
Allergy allergy = Context.getPatientService().getAllergy(activeListId);
Context.getPatientService().removeAllergy(allergy, reason);
}
/**
* Voids the Allergy
*
* @param activeListId
* @param reason
*/
public void voidAllergy(Integer activeListId, String reason) {
Allergy allergy = Context.getPatientService().getAllergy(activeListId);
if (reason == null) {
reason = "Error - user entered incorrect data from UI";
}
Context.getPatientService().voidAllergy(allergy, reason);
}
/**
* Creates a Problem Item
*
* @param patientId
* @param problemId
* @param status
* @param pStartDate
* @param comments
*/
public void createProblem(Integer patientId, Integer problemId, String status, String pStartDate, String comments) {
Patient patient = Context.getPatientService().getPatient(patientId);
Concept problemConcept = Context.getConceptService().getConcept(problemId);
ProblemModifier modifier = StringUtils.isBlank(status) ? null : ProblemModifier.valueOf(status);
Problem problem = new Problem(patient, problemConcept, parseDate(pStartDate), modifier, comments, null);
Context.getPatientService().saveProblem(problem);
}
/**
* Saves the Problem
*
* @param activeListId
* @param problemId
* @param status
* @param pStartDate
* @param comments
*/
public void saveProblem(Integer activeListId, Integer problemId, String status, String pStartDate, String comments) {
//get the allergy
Problem problem = Context.getPatientService().getProblem(activeListId);
problem.setProblem(Context.getConceptService().getConcept(problemId));
problem.setModifier(status);
problem.setStartDate(parseDate(pStartDate));
problem.setComments(comments);
Context.getPatientService().saveProblem(problem);
}
/**
* Remove a problem, sets the end date
*
* @param activeListId
* @param resolved
* @param reason
* @param pEndDate
*/
public void removeProblem(Integer activeListId, String reason, String pEndDate) {
Problem problem = Context.getPatientService().getProblem(activeListId);
problem.setEndDate(parseDate(pEndDate));
Context.getPatientService().removeProblem(problem, reason);
}
/**
* Voids the Problem
*
* @param activeListId
* @param reason
*/
public void voidProblem(Integer activeListId, String reason) {
Problem problem = Context.getPatientService().getProblem(activeListId);
if (reason == null) {
reason = "Error - user entered incorrect data from UI";
}
Context.getPatientService().voidProblem(problem, reason);
}
/**
* Simple utility method to parse the date object into the correct, local format
*
* @param date
* @return
*/
private Date parseDate(String date) {
if (date != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
return sdf.parse(date);
}
catch (ParseException e) {}
}
return null;
}
@Override
public boolean supportsPropertyName(String propertyName) {
return propertyName.equals(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS);
}
@Override
public void globalPropertyChanged(GlobalProperty newValue) {
try {
maximumResults = Integer.valueOf(newValue.getPropertyValue());
}
catch (NumberFormatException e) {
maximumResults = OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
}
@Override
public void globalPropertyDeleted(String propertyName) {
maximumResults = OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
/**
* Fetch the max results value from the global properties table
*
* @return Integer value for the person search max results global property
*/
private static Integer getMaximumSearchResults() {
try {
return Integer.valueOf(Context.getAdministrationService().getGlobalProperty(
OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS,
String.valueOf(OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE)));
}
catch (Exception e) {
log.warn("Unable to convert the global property " + OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS
+ "to a valid integer. Returning the default "
+ OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE);
}
return OpenmrsConstants.GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE;
}
}
| false | true | public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to process patient death - unable to proceed. Cause: " + e.getMessage();
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: " + e.getMessage();
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
| public String exitPatientFromCare(Integer patientId, Integer exitReasonId, String exitDateStr,
Integer causeOfDeathConceptId, String otherReason) {
log.debug("Entering exitfromcare with [" + patientId + "] [" + exitReasonId + "] [" + exitDateStr + "]");
String ret = "";
PatientService ps = Context.getPatientService();
ConceptService cs = Context.getConceptService();
Patient patient = null;
try {
patient = ps.getPatient(patientId);
}
catch (Exception e) {
patient = null;
}
if (patient == null) {
ret = "Unable to find valid patient with the supplied identification information - cannot exit patient from care";
}
// Get the exit reason concept (if possible)
Concept exitReasonConcept = null;
try {
exitReasonConcept = cs.getConcept(exitReasonId);
}
catch (Exception e) {
exitReasonConcept = null;
}
// Exit reason error handling
if (exitReasonConcept == null) {
ret = "Unable to locate reason for exit in dictionary - cannot exit patient from care";
}
// Parse the exit date
Date exitDate = null;
if (exitDateStr != null) {
SimpleDateFormat sdf = Context.getDateFormat();
try {
exitDate = sdf.parse(exitDateStr);
}
catch (ParseException e) {
exitDate = null;
}
}
// Exit date error handling
if (exitDate == null) {
ret = "Invalid date supplied - cannot exit patient from care without a valid date.";
}
// If all data is provided as expected
if (patient != null && exitReasonConcept != null && exitDate != null) {
// need to check first if this is death or not
String patientDiedConceptId = Context.getAdministrationService().getGlobalProperty("concept.patientDied");
Concept patientDiedConcept = null;
if (patientDiedConceptId != null) {
patientDiedConcept = cs.getConcept(patientDiedConceptId);
}
// If there is a concept for death in the dictionary
if (patientDiedConcept != null) {
// If the exist reason == patient died
if (exitReasonConcept.equals(patientDiedConcept)) {
Concept causeOfDeathConcept = null;
try {
causeOfDeathConcept = cs.getConcept(causeOfDeathConceptId);
}
catch (Exception e) {
causeOfDeathConcept = null;
}
// Cause of death concept exists
if (causeOfDeathConcept != null) {
try {
ps.processDeath(patient, exitDate, causeOfDeathConcept, otherReason);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to process patient death - unable to proceed. Cause: "
+ e.getMessage();
}
}
// cause of death concept does not exist
else {
ret = "Unable to locate cause of death in dictionary - cannot proceed";
}
}
// Otherwise, we process this as an exit
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
+ e.getMessage();
}
}
}
// If the system does not recognize death as a concept, then we exit from care
else {
try {
ps.exitFromCare(patient, exitDate, exitReasonConcept);
}
catch (Exception e) {
log.warn("Caught error", e);
ret = "Internal error while trying to exit patient from care - unable to exit patient from care at this time. Cause: "
+ e.getMessage();
}
}
log.debug("Exited from care, it seems");
}
return ret;
}
|
diff --git a/src/de/caluga/morphium/ObjectMapperImpl.java b/src/de/caluga/morphium/ObjectMapperImpl.java
index 73f5994..19d1cc0 100644
--- a/src/de/caluga/morphium/ObjectMapperImpl.java
+++ b/src/de/caluga/morphium/ObjectMapperImpl.java
@@ -1,635 +1,639 @@
package de.caluga.morphium;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import de.caluga.morphium.annotations.*;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
/**
* User: Stpehan Bösebeck
* Date: 26.03.12
* Time: 19:36
* <p/>
*/
public class ObjectMapperImpl implements ObjectMapper {
private static Logger log = Logger.getLogger(ObjectMapperImpl.class);
private static volatile Map<Class<?>, List<Field>> fieldCache = new Hashtable<Class<?>, List<Field>>();
public volatile Morphium morphium;
public Morphium getMorphium() {
return morphium;
}
public void setMorphium(Morphium morphium) {
this.morphium = morphium;
}
public ObjectMapperImpl(Morphium m) {
morphium = m;
}
public ObjectMapperImpl() {
this(null);
}
/**
* converts a sql/javascript-Name to Java, e.g. converts document_id to
* documentId.
*
* @param n
* @param capitalize : if true, first letter will be capitalized
* @return
*/
public String createCamelCase(String n, boolean capitalize) {
n = n.toLowerCase();
String f[] = n.split("_");
String ret = f[0].substring(0, 1).toLowerCase() + f[0].substring(1);
for (int i = 1; i < f.length; i++) {
ret = ret + f[i].substring(0, 1).toUpperCase() + f[i].substring(1);
}
if (capitalize) {
ret = ret.substring(0, 1).toUpperCase() + ret.substring(1);
}
return ret;
}
/**
* turns documentId into document_id
*
* @param n
* @return
*/
public String convertCamelCase(String n) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < n.length() - 1; i++) {
if (Character.isUpperCase(n.charAt(i)) && i > 0) {
b.append("_");
}
b.append(n.substring(i, i + 1).toLowerCase());
}
b.append(n.substring(n.length() - 1));
return b.toString();
}
@Override
public String getCollectionName(Class cls) {
if (!cls.isAnnotationPresent(Entity.class)) {
throw new IllegalArgumentException("No Entity " + cls.getSimpleName());
}
String name = cls.getSimpleName();
Entity p = (Entity) cls.getAnnotation(Entity.class);
if (p.useFQN()) {
name = cls.getName().replaceAll("\\.", "_");
}
if (!p.collectionName().equals(".")) {
name = p.collectionName();
} else {
if (p.translateCamelCase()) {
name = convertCamelCase(name);
}
}
return name;
}
@Override
public DBObject marshall(Object o) {
//recursively map object ot mongo-Object...
if (!isEntity(o)) {
throw new IllegalArgumentException("Object is no entity: " + o.getClass().getSimpleName());
}
DBObject dbo = new BasicDBObject();
if (o == null) {
return dbo;
}
List<String> flds = getFields(o.getClass());
Entity e = o.getClass().getAnnotation(Entity.class);
if (e.polymorph()) {
dbo.put("class_name", o.getClass().getName());
}
for (String f : flds) {
String fName = f;
try {
Field fld = getField(o.getClass(), f);
//do not store static fields!
if (Modifier.isStatic(fld.getModifiers())) {
continue;
}
if (fld.isAnnotationPresent(Id.class)) {
fName = "_id";
}
if (fld == null) {
log.error("Field not found " + f);
} else {
Object v = null;
Object value = fld.get(o);
if (fld.isAnnotationPresent(Reference.class)) {
Reference r = fld.getAnnotation(Reference.class);
//reference handling...
//field should point to a certain type - store ObjectID only
if (value == null) {
//no reference to be stored...
v = null;
} else {
v = getId(value);
if (v == null) {
//not stored yet
if (r.automaticStore()) {
//TODO: this could cause an endless loop!
if (morphium == null) {
log.fatal("Could not store - no Morphium set!");
} else {
morphium.store(value);
}
} else {
throw new IllegalArgumentException("Reference to be stored, that is null!");
}
v = getId(value);
}
}
} else {
//check, what type field has
//Store Entities recursively
//TODO: Fix recursion - this could cause a loop!
if (fld.getType().isAnnotationPresent(Entity.class)) {
if (value != null) {
DBObject obj = marshall(value);
obj.removeField("_id"); //Do not store ID embedded!
v = obj;
}
} else {
v = value;
if (v != null) {
if (v instanceof Map) {
//create MongoDBObject-Map
BasicDBObject dbMap = createDBMap((Map) v);
v = dbMap;
} else if (v instanceof List) {
BasicDBList lst = createDBList((List) v);
v = lst;
} else if (v instanceof Iterable) {
BasicDBList lst = new BasicDBList();
for (Object i : (Iterable) v) {
lst.add(i);
}
v = lst;
} else if (v.getClass().isEnum()) {
v = ((Enum) v).name();
}
}
}
}
if (v == null) {
if (fld.isAnnotationPresent(NotNull.class)) {
throw new IllegalArgumentException("Value is null - but must not (NotNull-Annotation to" + o.getClass().getSimpleName() + ")! Field: " + fName);
}
if (!fld.isAnnotationPresent(UseIfnull.class)) {
//Do not put null-Values into dbo => not storing null-Values to db
continue;
}
}
dbo.put(fName, v);
}
} catch (IllegalAccessException exc) {
log.fatal("Illegal Access to field " + f);
}
}
return dbo;
}
private BasicDBList createDBList(List v) {
BasicDBList lst = new BasicDBList();
for (Object lo : ((List) v)) {
if (lo.getClass().isAnnotationPresent(Entity.class)) {
DBObject marshall = marshall(lo);
marshall.put("class_name", lo.getClass().getName());
lst.add(marshall);
} else if (lo instanceof List) {
lst.add(createDBList((List) lo));
} else if (lo instanceof Map) {
lst.add(createDBMap(((Map) lo)));
} else {
lst.add(lo);
}
}
return lst;
}
private BasicDBObject createDBMap(Map v) {
BasicDBObject dbMap = new BasicDBObject();
for (Object k : ((Map) v).keySet()) {
if (!(k instanceof String)) {
log.warn("Map in Mongodb needs to have String as keys - using toString");
k = k.toString();
if (((String) k).contains(".")) {
log.warn(". not allowed as Key in Maps - converting to _");
k = ((String) k).replaceAll("\\.", "_");
}
}
Object mval = ((Map) v).get(k);
if (mval != null) {
if (mval.getClass().isAnnotationPresent(Entity.class)) {
DBObject obj = marshall(mval);
obj.put("class_name", mval.getClass().getName());
mval = obj;
} else if (mval instanceof Map) {
mval = createDBMap((Map) mval);
} else if (mval instanceof List) {
mval = createDBList((List) mval);
}
}
dbMap.put((String) k, mval);
}
return dbMap;
}
@Override
public <T> T unmarshall(Class<T> cls, DBObject o) {
try {
- if (o.get("class_name") != null) {
+ if (o.get("class_name") != null || o.get("className")!=null) {
log.info("overriding cls - it's defined in dbObject");
try {
- cls = (Class<T>) Class.forName((String) o.get("class_name"));
+ String cN=(String)o.get("class_name");
+ if (cN==null) {
+ cN = (String)o.get("className");
+ }
+ cls = (Class<T>) Class.forName(cN);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
T ret = cls.newInstance();
List<String> flds = getFields(cls);
for (String f : flds) {
Field fld = getField(cls, f);
if (Modifier.isStatic(fld.getModifiers())) {
//skip static fields
continue;
}
Object value = null;
if (!fld.getType().isAssignableFrom(Map.class) && !fld.getType().isAssignableFrom(List.class) && fld.isAnnotationPresent(Reference.class)) {
//A reference - only id stored
ObjectId id = (ObjectId) o.get(f);
if (morphium == null) {
log.fatal("Morphium not set - could not de-reference!");
} else {
Query q = morphium.createQueryFor(fld.getType());
q.f("_id").eq(id);
value = q.get();
}
} else if (fld.isAnnotationPresent(Id.class)) {
ObjectId id = (ObjectId) o.get("_id");
value = id;
} else if (fld.getType().isAnnotationPresent(Entity.class)) {
//entity! embedded
if (o.get(f) != null) {
value = unmarshall(fld.getType(), (DBObject) o.get(f));
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(Map.class)) {
BasicDBObject map = (BasicDBObject) o.get(f);
if (map != null) {
for (String n : map.keySet()) {
//TODO: recurse?
if (map.get(n) instanceof BasicDBObject) {
Object val = map.get(n);
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
map.put(n, unmarshall(ecls, (DBObject) map.get(n)));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
}
value = map;
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(List.class)) {
//TODO: recurse??
BasicDBList l = (BasicDBList) o.get(f);
List lst = new ArrayList();
if (l != null) {
for (Object val : l) {
if (val instanceof BasicDBObject) {
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
lst.add(unmarshall(ecls, (DBObject) val));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
//Probably an "normal" map
lst.add(val);
}
} else if (val instanceof DBRef) {
//todo: implement something
lst.add(((DBRef) val).getId());
} else {
lst.add(val);
}
}
value = lst;
} else {
value = l;
}
} else if (fld.getType().isEnum()) {
if (o.get(f) != null) {
value = Enum.valueOf((Class<? extends Enum>) fld.getType(), (String) o.get(f));
}
} else {
value = o.get(f);
}
setValue(ret, value, f);
}
flds = getFields(cls, Id.class);
if (flds.isEmpty()) {
throw new RuntimeException("Error - class does not have an ID field!");
}
getField(cls, flds.get(0)).set(ret, o.get("_id"));
return ret;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
//recursively fill class
}
@Override
public ObjectId getId(Object o) {
if (o == null) {
throw new IllegalArgumentException("Object cannot be null");
}
List<String> flds = getFields(o.getClass(), Id.class);
if (flds == null || flds.isEmpty()) {
throw new IllegalArgumentException("Object has no id defined: " + o.getClass().getSimpleName());
}
Field f = getField(o.getClass(), flds.get(0)); //first Id
if (f == null) {
throw new IllegalArgumentException("Object ID field not found " + o.getClass().getSimpleName());
}
try {
if (!(f.getType().equals(ObjectId.class))) {
throw new IllegalArgumentException("ID sould be of type ObjectId");
}
return (ObjectId) f.get(o);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private List<Field> getAllFields(Class cls) {
if (fieldCache.containsKey(cls)) {
return fieldCache.get(cls);
}
List<Field> ret = new Vector<Field>();
Class sc = cls;
//getting class hierachy
List<Class> hierachy = new Vector<Class>();
while (!sc.equals(Object.class)) {
hierachy.add(sc);
sc = sc.getSuperclass();
}
for (Class c : cls.getInterfaces()) {
hierachy.add(c);
}
//now we have a list of all classed up to Object
//we need to run through it in the right order
//in order to allow Inheritance to "shadow" fields
for (int i = hierachy.size() - 1; i >= 0; i--) {
Class c = hierachy.get(i);
for (Field f : c.getDeclaredFields()) {
ret.add(f);
}
}
fieldCache.put(cls, ret);
return ret;
}
@Override
/**
* get a list of valid fields of a given record as they are in the MongoDB
* so, if you have a field Mapping, the mapped Property-name will be used
* returns all fields, which have at least one of the given annotations
* if no annotation is given, all fields are returned
* Does not take the @Aliases-annotation int account
*
* @param cls
* @return
*/
public List<String> getFields(Class cls, Class<? extends Annotation>... annotations) {
List<String> ret = new Vector<String>();
Class sc = cls;
Entity entity = (Entity) sc.getAnnotation(Entity.class);
boolean tcc = entity.translateCamelCase();
//getting class hierachy
List<Field> fld = getAllFields(cls);
for (Field f : fld) {
if (annotations.length > 0) {
boolean found = false;
for (Class<? extends Annotation> a : annotations) {
if (f.isAnnotationPresent(a)) {
found = true;
break;
}
}
if (!found) {
//no annotation found
continue;
}
}
if (f.isAnnotationPresent(Reference.class) && !".".equals(f.getAnnotation(Reference.class).fieldName())) {
ret.add(f.getAnnotation(Reference.class).fieldName());
continue;
}
if (f.isAnnotationPresent(Property.class) && !".".equals(f.getAnnotation(Property.class).fieldName())) {
ret.add(f.getAnnotation(Property.class).fieldName());
continue;
}
// if (f.isAnnotationPresent(Id.class)) {
// ret.add(f.getName());
// continue;
// }
if (f.isAnnotationPresent(Transient.class)) {
continue;
}
if (tcc) {
ret.add(convertCamelCase(f.getName()));
} else {
ret.add(f.getName());
}
}
return ret;
}
@Override
public String getFieldName(Class cls, String field) {
Field f = getField(cls, field);
if (f.isAnnotationPresent(Property.class)) {
Property p = f.getAnnotation(Property.class);
if (p.fieldName() != null && !p.fieldName().equals(".")) {
return p.fieldName();
}
}
String fieldName = f.getName();
Entity ent = (Entity) cls.getAnnotation(Entity.class);
if (ent.translateCamelCase()) {
fieldName = convertCamelCase(fieldName);
}
return fieldName;
}
@Override
/**
* extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or
* the translated underscored lowercase name (mongoId => mongo_id) or a name specified in the Aliases-Annotation of this field
*
* @param cls - class to search
* @param fld - field name
* @return field, if found, null else
*/
public Field getField(Class cls, String fld) {
Entity entity = (Entity) cls.getAnnotation(Entity.class);
boolean tcc = entity.translateCamelCase();
List<Field> flds = getAllFields(cls);
for (Field f : flds) {
if (f.isAnnotationPresent(Property.class) && f.getAnnotation(Property.class).fieldName() != null && !".".equals(f.getAnnotation(Property.class).fieldName())) {
if (f.getAnnotation(Property.class).fieldName().equals(fld)) {
f.setAccessible(true);
return f;
}
}
if (f.isAnnotationPresent(Reference.class) && f.getAnnotation(Reference.class).fieldName() != null && !".".equals(f.getAnnotation(Reference.class).fieldName())) {
if (f.getAnnotation(Reference.class).fieldName().equals(fld)) {
f.setAccessible(true);
return f;
}
}
if (f.isAnnotationPresent(Aliases.class)) {
Aliases aliases = f.getAnnotation(Aliases.class);
String[] v = aliases.value();
for (String field : v) {
if (field.equals(fld)) {
f.setAccessible(true);
return f;
}
}
}
if (fld.equals("_id")) {
if (f.isAnnotationPresent(Id.class)) {
f.setAccessible(true);
return f;
}
}
if (f.getName().equals(fld)) {
if (tcc && !convertCamelCase(f.getName()).equals(fld)) {
throw new IllegalArgumentException("Error camel casing! " + fld + " != " + convertCamelCase(f.getName()));
}
f.setAccessible(true);
return f;
}
if (convertCamelCase(f.getName()).equals(fld)) {
f.setAccessible(true);
return f;
}
}
return null;
}
@Override
public boolean isEntity(Object o) {
if (o instanceof Class) {
return ((Class) o).isAnnotationPresent(Entity.class);
}
return o.getClass().isAnnotationPresent(Entity.class);
}
@Override
public Object getValue(Object o, String fld) {
if (o == null) {
return null;
}
try {
Field f = getField(o.getClass(), fld);
if (!Modifier.isStatic(f.getModifiers())) {
return f.get(o);
}
} catch (IllegalAccessException e) {
log.fatal("Illegal access to field " + fld + " of type " + o.getClass().getSimpleName());
}
return null;
}
@Override
public void setValue(Object o, Object value, String fld) {
if (o == null) {
return;
}
try {
Field f = getField(o.getClass(), fld);
if (!Modifier.isStatic(f.getModifiers())) {
try {
f.set(o, value);
} catch (Exception e) {
if (value == null) {
try {
//try to set 0 instead
f.set(o, 0);
} catch (Exception e1) {
//Still not working? Maybe boolean?
f.set(o, false);
}
}
}
}
} catch (Exception e) {
log.fatal("Illegal access to field " + fld + " of toype " + o.getClass().getSimpleName());
return;
}
}
}
| false | true | public <T> T unmarshall(Class<T> cls, DBObject o) {
try {
if (o.get("class_name") != null) {
log.info("overriding cls - it's defined in dbObject");
try {
cls = (Class<T>) Class.forName((String) o.get("class_name"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
T ret = cls.newInstance();
List<String> flds = getFields(cls);
for (String f : flds) {
Field fld = getField(cls, f);
if (Modifier.isStatic(fld.getModifiers())) {
//skip static fields
continue;
}
Object value = null;
if (!fld.getType().isAssignableFrom(Map.class) && !fld.getType().isAssignableFrom(List.class) && fld.isAnnotationPresent(Reference.class)) {
//A reference - only id stored
ObjectId id = (ObjectId) o.get(f);
if (morphium == null) {
log.fatal("Morphium not set - could not de-reference!");
} else {
Query q = morphium.createQueryFor(fld.getType());
q.f("_id").eq(id);
value = q.get();
}
} else if (fld.isAnnotationPresent(Id.class)) {
ObjectId id = (ObjectId) o.get("_id");
value = id;
} else if (fld.getType().isAnnotationPresent(Entity.class)) {
//entity! embedded
if (o.get(f) != null) {
value = unmarshall(fld.getType(), (DBObject) o.get(f));
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(Map.class)) {
BasicDBObject map = (BasicDBObject) o.get(f);
if (map != null) {
for (String n : map.keySet()) {
//TODO: recurse?
if (map.get(n) instanceof BasicDBObject) {
Object val = map.get(n);
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
map.put(n, unmarshall(ecls, (DBObject) map.get(n)));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
}
value = map;
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(List.class)) {
//TODO: recurse??
BasicDBList l = (BasicDBList) o.get(f);
List lst = new ArrayList();
if (l != null) {
for (Object val : l) {
if (val instanceof BasicDBObject) {
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
lst.add(unmarshall(ecls, (DBObject) val));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
//Probably an "normal" map
lst.add(val);
}
} else if (val instanceof DBRef) {
//todo: implement something
lst.add(((DBRef) val).getId());
} else {
lst.add(val);
}
}
value = lst;
} else {
value = l;
}
} else if (fld.getType().isEnum()) {
if (o.get(f) != null) {
value = Enum.valueOf((Class<? extends Enum>) fld.getType(), (String) o.get(f));
}
} else {
value = o.get(f);
}
setValue(ret, value, f);
}
flds = getFields(cls, Id.class);
if (flds.isEmpty()) {
throw new RuntimeException("Error - class does not have an ID field!");
}
getField(cls, flds.get(0)).set(ret, o.get("_id"));
return ret;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
//recursively fill class
}
| public <T> T unmarshall(Class<T> cls, DBObject o) {
try {
if (o.get("class_name") != null || o.get("className")!=null) {
log.info("overriding cls - it's defined in dbObject");
try {
String cN=(String)o.get("class_name");
if (cN==null) {
cN = (String)o.get("className");
}
cls = (Class<T>) Class.forName(cN);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
T ret = cls.newInstance();
List<String> flds = getFields(cls);
for (String f : flds) {
Field fld = getField(cls, f);
if (Modifier.isStatic(fld.getModifiers())) {
//skip static fields
continue;
}
Object value = null;
if (!fld.getType().isAssignableFrom(Map.class) && !fld.getType().isAssignableFrom(List.class) && fld.isAnnotationPresent(Reference.class)) {
//A reference - only id stored
ObjectId id = (ObjectId) o.get(f);
if (morphium == null) {
log.fatal("Morphium not set - could not de-reference!");
} else {
Query q = morphium.createQueryFor(fld.getType());
q.f("_id").eq(id);
value = q.get();
}
} else if (fld.isAnnotationPresent(Id.class)) {
ObjectId id = (ObjectId) o.get("_id");
value = id;
} else if (fld.getType().isAnnotationPresent(Entity.class)) {
//entity! embedded
if (o.get(f) != null) {
value = unmarshall(fld.getType(), (DBObject) o.get(f));
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(Map.class)) {
BasicDBObject map = (BasicDBObject) o.get(f);
if (map != null) {
for (String n : map.keySet()) {
//TODO: recurse?
if (map.get(n) instanceof BasicDBObject) {
Object val = map.get(n);
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
map.put(n, unmarshall(ecls, (DBObject) map.get(n)));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
}
value = map;
} else {
value = null;
}
} else if (fld.getType().isAssignableFrom(List.class)) {
//TODO: recurse??
BasicDBList l = (BasicDBList) o.get(f);
List lst = new ArrayList();
if (l != null) {
for (Object val : l) {
if (val instanceof BasicDBObject) {
if (((BasicDBObject) val).containsField("class_name") || ((BasicDBObject) val).containsField("className")) {
//Entity to map!
String cn = (String) ((BasicDBObject) val).get("class_name");
if (cn == null) {
cn = (String) ((BasicDBObject) val).get("className");
}
try {
Class ecls = Class.forName(cn);
lst.add(unmarshall(ecls, (DBObject) val));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
//Probably an "normal" map
lst.add(val);
}
} else if (val instanceof DBRef) {
//todo: implement something
lst.add(((DBRef) val).getId());
} else {
lst.add(val);
}
}
value = lst;
} else {
value = l;
}
} else if (fld.getType().isEnum()) {
if (o.get(f) != null) {
value = Enum.valueOf((Class<? extends Enum>) fld.getType(), (String) o.get(f));
}
} else {
value = o.get(f);
}
setValue(ret, value, f);
}
flds = getFields(cls, Id.class);
if (flds.isEmpty()) {
throw new RuntimeException("Error - class does not have an ID field!");
}
getField(cls, flds.get(0)).set(ret, o.get("_id"));
return ret;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
//recursively fill class
}
|
diff --git a/source/de/anomic/yacy/yacyTray.java b/source/de/anomic/yacy/yacyTray.java
index 6a5e08c12..c75ffd314 100644
--- a/source/de/anomic/yacy/yacyTray.java
+++ b/source/de/anomic/yacy/yacyTray.java
@@ -1,150 +1,150 @@
// yacyTray.java
// (C) 2008 by David Wieditz; [email protected]
// first published 13.07.2008 on http://yacy.net
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: $
// $LastChangedRevision: $
// $LastChangedBy: $
//
// 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
package de.anomic.yacy;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import org.jdesktop.jdic.tray.SystemTray;
import org.jdesktop.jdic.tray.TrayIcon;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverSystem;
public class yacyTray implements ActionListener, ItemListener {
private boolean testing = false;
plasmaSwitchboard sb;
public static boolean isShown = false;
public static boolean lockBrowserPopup = true;
private long t1;
private static SystemTray tray;
private static TrayIcon ti;
public yacyTray(plasmaSwitchboard sb, boolean showmenu) {
this.sb = sb;
- final SystemTray tray = SystemTray.getDefaultSystemTray();
+ tray = SystemTray.getDefaultSystemTray();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
if( Integer.parseInt(System.getProperty("java.version").substring(2,3)) >=5 )
System.setProperty("javax.swing.adjustPopupLocationToFit", "false");
JPopupMenu menu;
JMenuItem menuItem;
final String iconpath = sb.getRootPath().toString() + "/addon/YaCy_TrayIcon.gif".replace("/", File.separator);
final ImageIcon i = new ImageIcon(iconpath);
// the menu is disabled because of visibility conflicts on windows with jre6
// anyway the code might be a template for future use
if (showmenu) {
// this is the popup menu
menu = new JPopupMenu("YaCy");
// YaCy Search
menuItem = new JMenuItem("YaCy Search");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser("");
}
});
menu.add(menuItem);
// Quit
if (testing) {
menu.addSeparator();
menuItem = new JMenuItem("Quit");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(menuItem);
}
// Tray Icon
ti = new TrayIcon(i, "YaCy", menu);
} else {
ti = new TrayIcon(i, "YaCy");
}
ti.setIconAutoSize(true);
ti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayClickAction();
}
});
tray.addTrayIcon(ti);
isShown = true;
}
private void trayClickAction(){ //detect doubleclick
if(System.currentTimeMillis() - t1 < 500){
if (lockBrowserPopup) {
displayBalloonMessage("YaCy","Please wait until YaCy is started.");
} else {
openBrowser("");
}
t1 = 0; //protecting against tripleclick
} else { t1 = System.currentTimeMillis(); }
}
private void openBrowser(String browserPopUpPage){
// no need for https, because we are on localhost
serverSystem.openBrowser("http://localhost:" + sb.getConfig("port", "8080") + "/" + browserPopUpPage);
}
public void removeTray(){
tray.removeTrayIcon(ti);
isShown = false;
}
public void displayBalloonMessage(String title, String message){
ti.displayMessage(title, message, 0);
}
public void actionPerformed(ActionEvent e) { }
public void itemStateChanged(ItemEvent e) { }
}
| true | true | public yacyTray(plasmaSwitchboard sb, boolean showmenu) {
this.sb = sb;
final SystemTray tray = SystemTray.getDefaultSystemTray();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
if( Integer.parseInt(System.getProperty("java.version").substring(2,3)) >=5 )
System.setProperty("javax.swing.adjustPopupLocationToFit", "false");
JPopupMenu menu;
JMenuItem menuItem;
final String iconpath = sb.getRootPath().toString() + "/addon/YaCy_TrayIcon.gif".replace("/", File.separator);
final ImageIcon i = new ImageIcon(iconpath);
// the menu is disabled because of visibility conflicts on windows with jre6
// anyway the code might be a template for future use
if (showmenu) {
// this is the popup menu
menu = new JPopupMenu("YaCy");
// YaCy Search
menuItem = new JMenuItem("YaCy Search");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser("");
}
});
menu.add(menuItem);
// Quit
if (testing) {
menu.addSeparator();
menuItem = new JMenuItem("Quit");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(menuItem);
}
// Tray Icon
ti = new TrayIcon(i, "YaCy", menu);
} else {
ti = new TrayIcon(i, "YaCy");
}
ti.setIconAutoSize(true);
ti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayClickAction();
}
});
tray.addTrayIcon(ti);
isShown = true;
}
| public yacyTray(plasmaSwitchboard sb, boolean showmenu) {
this.sb = sb;
tray = SystemTray.getDefaultSystemTray();
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
if( Integer.parseInt(System.getProperty("java.version").substring(2,3)) >=5 )
System.setProperty("javax.swing.adjustPopupLocationToFit", "false");
JPopupMenu menu;
JMenuItem menuItem;
final String iconpath = sb.getRootPath().toString() + "/addon/YaCy_TrayIcon.gif".replace("/", File.separator);
final ImageIcon i = new ImageIcon(iconpath);
// the menu is disabled because of visibility conflicts on windows with jre6
// anyway the code might be a template for future use
if (showmenu) {
// this is the popup menu
menu = new JPopupMenu("YaCy");
// YaCy Search
menuItem = new JMenuItem("YaCy Search");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser("");
}
});
menu.add(menuItem);
// Quit
if (testing) {
menu.addSeparator();
menuItem = new JMenuItem("Quit");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(menuItem);
}
// Tray Icon
ti = new TrayIcon(i, "YaCy", menu);
} else {
ti = new TrayIcon(i, "YaCy");
}
ti.setIconAutoSize(true);
ti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
trayClickAction();
}
});
tray.addTrayIcon(ti);
isShown = true;
}
|
diff --git a/src/main/java/org/primefaces/extensions/component/ajaxerrorhandler/AjaxExceptionHandler.java b/src/main/java/org/primefaces/extensions/component/ajaxerrorhandler/AjaxExceptionHandler.java
index 84c8a391..4448eb64 100644
--- a/src/main/java/org/primefaces/extensions/component/ajaxerrorhandler/AjaxExceptionHandler.java
+++ b/src/main/java/org/primefaces/extensions/component/ajaxerrorhandler/AjaxExceptionHandler.java
@@ -1,267 +1,271 @@
/*
* Copyright 2011-2012 PrimeFaces Extensions.
*
* 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.
*
* $Id$
*/
package org.primefaces.extensions.component.ajaxerrorhandler;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitContext;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.PartialResponseWriter;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.view.ViewDeclarationLanguage;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.exception.ExceptionUtils;
/**
* {@link ExceptionHandlerWrapper} which writes a custom XML response for the {@link AjaxErrorHandler} component.
*
* @author Pavol Slany / last modified by $Author$
* @version $Revision$
* @since 0.5
*/
public class AjaxExceptionHandler extends ExceptionHandlerWrapper {
private static final Logger LOGGER = Logger.getLogger(AjaxExceptionHandler.class.getCanonicalName());
private ExceptionHandler wrapped = null;
/**
* Construct a new {@link AjaxExceptionHandler} around the given wrapped {@link ExceptionHandler}.
*
* @param wrapped The wrapped {@link ExceptionHandler}.
*/
public AjaxExceptionHandler(final ExceptionHandler wrapped) {
this.wrapped = wrapped;
}
@Override
public ExceptionHandler getWrapped() {
return wrapped;
}
@Override
public void handle() throws FacesException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getPartialViewContext()!=null && context.getPartialViewContext().isAjaxRequest()) {
Iterable<ExceptionQueuedEvent> exceptionQueuedEvents = getUnhandledExceptionQueuedEvents();
if (exceptionQueuedEvents!=null && exceptionQueuedEvents.iterator()!=null) {
Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents = getUnhandledExceptionQueuedEvents().iterator();
if (unhandledExceptionQueuedEvents.hasNext()) {
Throwable exception = unhandledExceptionQueuedEvents.next().getContext().getException();
unhandledExceptionQueuedEvents.remove();
handlePartialResponseError(context, exception);
}
while (unhandledExceptionQueuedEvents.hasNext()) {
// Any remaining unhandled exceptions are not interesting. First fix the first.
unhandledExceptionQueuedEvents.next();
unhandledExceptionQueuedEvents.remove();
}
}
}
wrapped.handle();
}
private void handlePartialResponseError(final FacesContext context, final Throwable t) {
if (context.getResponseComplete()) {
return; // don't write anything if the response is complete
}
if (!context.getExternalContext().isResponseCommitted()) {
context.getExternalContext().responseReset();
}
try {
Throwable rootCause = ExceptionUtils.getRootCause(t);
// Workaround for ViewExpiredException if UIViewRoot was not restored ...
if (context.getViewRoot() == null) {
try {
String uri = ((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI();
UIViewRoot viewRoot = context.getApplication().getViewHandler().createView(context, uri);
context.setViewRoot(viewRoot);
// Workaround for Mojarra : if UIViewRoot == null (VIEW is lost in session), throwed is IllegalArgumentException instead of 'ViewExpiredException'
if (rootCause==null && t instanceof IllegalArgumentException) {
rootCause = new javax.faces.application.ViewExpiredException(uri);
}
// buildView - create component tree in view ...
// todo: add CONTEXT-PARAM for set this feature BUILD VIEW
String viewId = viewRoot.getViewId();
ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, viewId);
vdl.buildView(context, viewRoot);
}
catch (Exception tt) {
LOGGER.log(Level.SEVERE, tt.getMessage(), tt);
}
}
String errorName = (rootCause == null) ? t.getClass().getCanonicalName() : rootCause.getClass().getCanonicalName();
+ LOGGER.log(Level.SEVERE, ""+t.getMessage(), t);
ExternalContext extContext = context.getExternalContext();
extContext.addResponseHeader("Content-Type", "text/xml; charset="+extContext.getRequestCharacterEncoding());
extContext.addResponseHeader("Cache-Control", "no-cache");
extContext.setResponseCharacterEncoding(extContext.getRequestCharacterEncoding());
extContext.setResponseContentType("text/xml");
PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
writer.startDocument();
writer.startElement("error", null);
// Node <error-name>
writer.startElement("error-name", null);
writer.write(errorName);
writer.endElement("error-name");
// Node <error-message>
writer.startElement("error-message", null);
writer.startCDATA();
- writer.write(rootCause != null ? rootCause.getMessage() : t.getMessage());
+ String message = rootCause != null && rootCause.getMessage()!=null ? rootCause.getMessage() : t.getMessage();
+ if (message == null) message = "";
+ writer.write(message);
writer.endCDATA();
writer.endElement("error-message");
// Node <error-stacktrace>
writer.startElement("error-stacktrace", null);
writer.startCDATA();
String stackTrace = ExceptionUtils.getStackTrace(rootCause == null? t : rootCause);
+ if (stackTrace == null) stackTrace = "";
writer.write(stackTrace);
writer.endCDATA();
writer.endElement("error-stacktrace");
// Node <error-stacktrace>
writer.startElement("error-hostname", null);
writer.write(getHostname());
writer.endElement("error-hostname");
UIViewRoot root = context.getViewRoot();
AjaxErrorHandlerVisitCallback visitCallback = new AjaxErrorHandlerVisitCallback(errorName);
if (root != null)
root.visitTree(VisitContext.createVisitContext(context), visitCallback);
UIComponent titleFacet = visitCallback.findCurrentTitleFacet();
if (titleFacet != null) {
writer.startElement("updateTitle", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
titleFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering titleUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateTitle");
}
UIComponent bodyFacet = visitCallback.findCurrentBodyFacet();
if (bodyFacet != null) {
writer.startElement("updateBody", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
bodyFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering bodyUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateBody");
}
List<UIComponent> customContent = visitCallback.findCurrentChildren();
if (customContent != null && customContent.size() > 0) {
writer.startElement("updateCustomContent", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
for (UIComponent component : customContent) {
component.encodeAll(context);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateCustomContent in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateCustomContent");
}
/*
// Update state - is ignored, because ajaxerrorhandler.js is not ready for this update ...
if (!context.getViewRoot().isTransient()) {
// Get the view state and write it to the response..
writer.startElement("updateViewState", null);
writer.startCDATA();
try {
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateViewState in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateViewState");
}
*/
writer.endElement("error");
writer.endDocument();
context.responseComplete();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
protected String getHostname() throws UnknownHostException {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "???unknown???";
}
}
}
| false | true | private void handlePartialResponseError(final FacesContext context, final Throwable t) {
if (context.getResponseComplete()) {
return; // don't write anything if the response is complete
}
if (!context.getExternalContext().isResponseCommitted()) {
context.getExternalContext().responseReset();
}
try {
Throwable rootCause = ExceptionUtils.getRootCause(t);
// Workaround for ViewExpiredException if UIViewRoot was not restored ...
if (context.getViewRoot() == null) {
try {
String uri = ((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI();
UIViewRoot viewRoot = context.getApplication().getViewHandler().createView(context, uri);
context.setViewRoot(viewRoot);
// Workaround for Mojarra : if UIViewRoot == null (VIEW is lost in session), throwed is IllegalArgumentException instead of 'ViewExpiredException'
if (rootCause==null && t instanceof IllegalArgumentException) {
rootCause = new javax.faces.application.ViewExpiredException(uri);
}
// buildView - create component tree in view ...
// todo: add CONTEXT-PARAM for set this feature BUILD VIEW
String viewId = viewRoot.getViewId();
ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, viewId);
vdl.buildView(context, viewRoot);
}
catch (Exception tt) {
LOGGER.log(Level.SEVERE, tt.getMessage(), tt);
}
}
String errorName = (rootCause == null) ? t.getClass().getCanonicalName() : rootCause.getClass().getCanonicalName();
ExternalContext extContext = context.getExternalContext();
extContext.addResponseHeader("Content-Type", "text/xml; charset="+extContext.getRequestCharacterEncoding());
extContext.addResponseHeader("Cache-Control", "no-cache");
extContext.setResponseCharacterEncoding(extContext.getRequestCharacterEncoding());
extContext.setResponseContentType("text/xml");
PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
writer.startDocument();
writer.startElement("error", null);
// Node <error-name>
writer.startElement("error-name", null);
writer.write(errorName);
writer.endElement("error-name");
// Node <error-message>
writer.startElement("error-message", null);
writer.startCDATA();
writer.write(rootCause != null ? rootCause.getMessage() : t.getMessage());
writer.endCDATA();
writer.endElement("error-message");
// Node <error-stacktrace>
writer.startElement("error-stacktrace", null);
writer.startCDATA();
String stackTrace = ExceptionUtils.getStackTrace(rootCause == null? t : rootCause);
writer.write(stackTrace);
writer.endCDATA();
writer.endElement("error-stacktrace");
// Node <error-stacktrace>
writer.startElement("error-hostname", null);
writer.write(getHostname());
writer.endElement("error-hostname");
UIViewRoot root = context.getViewRoot();
AjaxErrorHandlerVisitCallback visitCallback = new AjaxErrorHandlerVisitCallback(errorName);
if (root != null)
root.visitTree(VisitContext.createVisitContext(context), visitCallback);
UIComponent titleFacet = visitCallback.findCurrentTitleFacet();
if (titleFacet != null) {
writer.startElement("updateTitle", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
titleFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering titleUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateTitle");
}
UIComponent bodyFacet = visitCallback.findCurrentBodyFacet();
if (bodyFacet != null) {
writer.startElement("updateBody", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
bodyFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering bodyUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateBody");
}
List<UIComponent> customContent = visitCallback.findCurrentChildren();
if (customContent != null && customContent.size() > 0) {
writer.startElement("updateCustomContent", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
for (UIComponent component : customContent) {
component.encodeAll(context);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateCustomContent in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateCustomContent");
}
/*
// Update state - is ignored, because ajaxerrorhandler.js is not ready for this update ...
if (!context.getViewRoot().isTransient()) {
// Get the view state and write it to the response..
writer.startElement("updateViewState", null);
writer.startCDATA();
try {
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateViewState in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateViewState");
}
*/
writer.endElement("error");
writer.endDocument();
context.responseComplete();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
| private void handlePartialResponseError(final FacesContext context, final Throwable t) {
if (context.getResponseComplete()) {
return; // don't write anything if the response is complete
}
if (!context.getExternalContext().isResponseCommitted()) {
context.getExternalContext().responseReset();
}
try {
Throwable rootCause = ExceptionUtils.getRootCause(t);
// Workaround for ViewExpiredException if UIViewRoot was not restored ...
if (context.getViewRoot() == null) {
try {
String uri = ((HttpServletRequest) context.getExternalContext().getRequest()).getRequestURI();
UIViewRoot viewRoot = context.getApplication().getViewHandler().createView(context, uri);
context.setViewRoot(viewRoot);
// Workaround for Mojarra : if UIViewRoot == null (VIEW is lost in session), throwed is IllegalArgumentException instead of 'ViewExpiredException'
if (rootCause==null && t instanceof IllegalArgumentException) {
rootCause = new javax.faces.application.ViewExpiredException(uri);
}
// buildView - create component tree in view ...
// todo: add CONTEXT-PARAM for set this feature BUILD VIEW
String viewId = viewRoot.getViewId();
ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, viewId);
vdl.buildView(context, viewRoot);
}
catch (Exception tt) {
LOGGER.log(Level.SEVERE, tt.getMessage(), tt);
}
}
String errorName = (rootCause == null) ? t.getClass().getCanonicalName() : rootCause.getClass().getCanonicalName();
LOGGER.log(Level.SEVERE, ""+t.getMessage(), t);
ExternalContext extContext = context.getExternalContext();
extContext.addResponseHeader("Content-Type", "text/xml; charset="+extContext.getRequestCharacterEncoding());
extContext.addResponseHeader("Cache-Control", "no-cache");
extContext.setResponseCharacterEncoding(extContext.getRequestCharacterEncoding());
extContext.setResponseContentType("text/xml");
PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
writer.startDocument();
writer.startElement("error", null);
// Node <error-name>
writer.startElement("error-name", null);
writer.write(errorName);
writer.endElement("error-name");
// Node <error-message>
writer.startElement("error-message", null);
writer.startCDATA();
String message = rootCause != null && rootCause.getMessage()!=null ? rootCause.getMessage() : t.getMessage();
if (message == null) message = "";
writer.write(message);
writer.endCDATA();
writer.endElement("error-message");
// Node <error-stacktrace>
writer.startElement("error-stacktrace", null);
writer.startCDATA();
String stackTrace = ExceptionUtils.getStackTrace(rootCause == null? t : rootCause);
if (stackTrace == null) stackTrace = "";
writer.write(stackTrace);
writer.endCDATA();
writer.endElement("error-stacktrace");
// Node <error-stacktrace>
writer.startElement("error-hostname", null);
writer.write(getHostname());
writer.endElement("error-hostname");
UIViewRoot root = context.getViewRoot();
AjaxErrorHandlerVisitCallback visitCallback = new AjaxErrorHandlerVisitCallback(errorName);
if (root != null)
root.visitTree(VisitContext.createVisitContext(context), visitCallback);
UIComponent titleFacet = visitCallback.findCurrentTitleFacet();
if (titleFacet != null) {
writer.startElement("updateTitle", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
titleFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering titleUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateTitle");
}
UIComponent bodyFacet = visitCallback.findCurrentBodyFacet();
if (bodyFacet != null) {
writer.startElement("updateBody", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
bodyFacet.encodeAll(context);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering bodyUpdate in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateBody");
}
List<UIComponent> customContent = visitCallback.findCurrentChildren();
if (customContent != null && customContent.size() > 0) {
writer.startElement("updateCustomContent", null);
writer.startCDATA();
try {
context.setResponseWriter(writer);
for (UIComponent component : customContent) {
component.encodeAll(context);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateCustomContent in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateCustomContent");
}
/*
// Update state - is ignored, because ajaxerrorhandler.js is not ready for this update ...
if (!context.getViewRoot().isTransient()) {
// Get the view state and write it to the response..
writer.startElement("updateViewState", null);
writer.startCDATA();
try {
String state = context.getApplication().getStateManager().getViewState(context);
writer.write(state);
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Rendering updateViewState in AjaxExceptionHandler throws exception!", e);
writer.write("<exception />");
}
writer.endCDATA();
writer.endElement("updateViewState");
}
*/
writer.endElement("error");
writer.endDocument();
context.responseComplete();
} catch (IOException e) {
if (LOGGER.isLoggable(Level.SEVERE)) {
LOGGER.log(Level.SEVERE, e.getMessage(), e);
}
}
}
|
diff --git a/src/plugins/org.drftpd.commands.request/src/org/drftpd/commands/request/RequestPreHook.java b/src/plugins/org.drftpd.commands.request/src/org/drftpd/commands/request/RequestPreHook.java
index e56647cf..395904b7 100644
--- a/src/plugins/org.drftpd.commands.request/src/org/drftpd/commands/request/RequestPreHook.java
+++ b/src/plugins/org.drftpd.commands.request/src/org/drftpd/commands/request/RequestPreHook.java
@@ -1,74 +1,74 @@
/*
* This file is part of DrFTPD, Distributed FTP Daemon.
*
* DrFTPD 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.
*
* DrFTPD 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 DrFTPD; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.drftpd.commands.request;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;
import org.drftpd.GlobalContext;
import org.drftpd.commandmanager.PreHookInterface;
import org.drftpd.commandmanager.StandardCommandManager;
import org.drftpd.commandmanager.CommandRequest;
import org.drftpd.commandmanager.CommandRequestInterface;
import org.drftpd.commandmanager.CommandResponse;
import org.drftpd.commands.request.metadata.RequestUserData;
import org.drftpd.event.ReloadEvent;
import org.drftpd.permissions.Permission;
import org.drftpd.usermanager.User;
import java.util.Properties;
/**
* @author scitz0
* @version $Id$
*/
public class RequestPreHook implements PreHookInterface {
private int _weekMax;
private Permission _weekExempt;
public void initialize(StandardCommandManager cManager) {
readConfig();
// Subscribe to events
AnnotationProcessor.process(this);
}
public CommandRequestInterface doWklyAllotmentPreCheck(CommandRequest request) {
User user = request.getSession().getUserNull(request.getUser());
- int weekReqs = user.getKeyedMap().getObjectInteger(RequestUserData.WEEKREQS);
+ int weekReqs = user.getKeyedMap().getObject(RequestUserData.WEEKREQS,0);
if (_weekMax != 0 && weekReqs >= _weekMax && !_weekExempt.check(user)) {
// User is not exempted and max number of request this week is made already
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - " +
"You have reached max(" + _weekMax + ") number of requests per week"));
}
return request;
}
/**
* Reads 'conf/plugins/request.conf'
*/
private void readConfig() {
Properties props = GlobalContext.getGlobalContext().getPluginsConfig().getPropertiesForPlugin("request");
_weekMax = Integer.parseInt(props.getProperty("request.weekmax", "0"));
_weekExempt = new Permission(props.getProperty("request.weekexempt", ""));
}
@EventSubscriber
public void onReloadEvent(ReloadEvent event) {
readConfig();
}
}
| true | true | public CommandRequestInterface doWklyAllotmentPreCheck(CommandRequest request) {
User user = request.getSession().getUserNull(request.getUser());
int weekReqs = user.getKeyedMap().getObjectInteger(RequestUserData.WEEKREQS);
if (_weekMax != 0 && weekReqs >= _weekMax && !_weekExempt.check(user)) {
// User is not exempted and max number of request this week is made already
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - " +
"You have reached max(" + _weekMax + ") number of requests per week"));
}
return request;
}
| public CommandRequestInterface doWklyAllotmentPreCheck(CommandRequest request) {
User user = request.getSession().getUserNull(request.getUser());
int weekReqs = user.getKeyedMap().getObject(RequestUserData.WEEKREQS,0);
if (_weekMax != 0 && weekReqs >= _weekMax && !_weekExempt.check(user)) {
// User is not exempted and max number of request this week is made already
request.setAllowed(false);
request.setDeniedResponse(new CommandResponse(530, "Access denied - " +
"You have reached max(" + _weekMax + ") number of requests per week"));
}
return request;
}
|
diff --git a/src/com/massivecraft/factions/integration/LWCFeatures.java b/src/com/massivecraft/factions/integration/LWCFeatures.java
index 837b7094..9cacb807 100644
--- a/src/com/massivecraft/factions/integration/LWCFeatures.java
+++ b/src/com/massivecraft/factions/integration/LWCFeatures.java
@@ -1,86 +1,86 @@
package com.massivecraft.factions.integration;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import com.griefcraft.lwc.LWC;
import com.griefcraft.lwc.LWCPlugin;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.FPlayers;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.P;
public class LWCFeatures
{
private static LWC lwc;
public static void integrateLWC(LWCPlugin test)
{
lwc = test.getLWC();
P.p.log("Successfully hooked into LWC!"+(Conf.lwcIntegration ? "" : " Integration is currently disabled, though (\"lwcIntegration\")."));
}
public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
- if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getBukkitOwner())))
+ if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static void clearAllChests(FLocation flocation)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
lwc.findProtection(chests.get(x)).remove();
}
}
}
public static boolean getEnabled()
{
return Conf.lwcIntegration && lwc != null;
}
}
| true | true | public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getBukkitOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
| public static void clearOtherChests(FLocation flocation, Faction faction)
{
Location location = new Location(Bukkit.getWorld(flocation.getWorldName()), flocation.getX() * 16, 5, flocation.getZ() * 16);
Chunk chunk = location.getChunk();
BlockState[] blocks = chunk.getTileEntities();
List<Block> chests = new LinkedList<Block>();
for(int x = 0; x < blocks.length; x++)
{
if(blocks[x].getType() == Material.CHEST)
{
chests.add(blocks[x].getBlock());
}
}
for(int x = 0; x < chests.size(); x++)
{
if(lwc.findProtection(chests.get(x)) != null)
{
if(!faction.getFPlayers().contains(FPlayers.i.get(lwc.findProtection(chests.get(x)).getOwner())))
lwc.findProtection(chests.get(x)).remove();
}
}
}
|
diff --git a/tests/src/com/android/gallery3d/exif/ExifXmlDataTestCase.java b/tests/src/com/android/gallery3d/exif/ExifXmlDataTestCase.java
index 5b61778bd..6a4d29e98 100644
--- a/tests/src/com/android/gallery3d/exif/ExifXmlDataTestCase.java
+++ b/tests/src/com/android/gallery3d/exif/ExifXmlDataTestCase.java
@@ -1,91 +1,95 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.exif;
import android.content.res.Resources;
import android.test.InstrumentationTestCase;
import android.util.Xml;
import org.xmlpull.v1.XmlPullParser;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ExifXmlDataTestCase extends InstrumentationTestCase {
private static final String RES_ID_TITLE = "Resource ID: %x";
private InputStream mImageInputStream;
private InputStream mXmlInputStream;
private XmlPullParser mXmlParser;
private final String mImagePath;
private final String mXmlPath;
private final int mImageResourceId;
private final int mXmlResourceId;
public ExifXmlDataTestCase(int imageRes, int xmlRes) {
mImagePath = null;
mXmlPath = null;
mImageResourceId = imageRes;
mXmlResourceId = xmlRes;
}
public ExifXmlDataTestCase(String imagePath, String xmlPath) {
mImagePath = imagePath;
mXmlPath = xmlPath;
mImageResourceId = 0;
mXmlResourceId = 0;
}
protected InputStream getImageInputStream() {
return mImageInputStream;
}
protected XmlPullParser getXmlParser() {
return mXmlParser;
}
@Override
public void setUp() throws Exception {
- if (mImagePath != null) {
- mImageInputStream = new FileInputStream(mImagePath);
- mXmlInputStream = new FileInputStream(mXmlPath);
- mXmlParser = Xml.newPullParser();
- mXmlParser.setInput(new InputStreamReader(mXmlInputStream));
- } else {
- Resources res = getInstrumentation().getContext().getResources();
- mImageInputStream = res.openRawResource(mImageResourceId);
- mXmlParser = res.getXml(mXmlResourceId);
+ try {
+ if (mImagePath != null) {
+ mImageInputStream = new FileInputStream(mImagePath);
+ mXmlInputStream = new FileInputStream(mXmlPath);
+ mXmlParser = Xml.newPullParser();
+ mXmlParser.setInput(new InputStreamReader(mXmlInputStream));
+ } else {
+ Resources res = getInstrumentation().getContext().getResources();
+ mImageInputStream = res.openRawResource(mImageResourceId);
+ mXmlParser = res.getXml(mXmlResourceId);
+ }
+ } catch (Exception e) {
+ throw new Exception(getImageTitle(), e);
}
}
@Override
public void tearDown() throws Exception {
Util.closeSilently(mImageInputStream);
Util.closeSilently(mXmlInputStream);
}
protected String getImageTitle() {
if (mImagePath != null) {
return mImagePath;
} else {
return String.format(RES_ID_TITLE, mImageResourceId);
}
}
}
| true | true | public void setUp() throws Exception {
if (mImagePath != null) {
mImageInputStream = new FileInputStream(mImagePath);
mXmlInputStream = new FileInputStream(mXmlPath);
mXmlParser = Xml.newPullParser();
mXmlParser.setInput(new InputStreamReader(mXmlInputStream));
} else {
Resources res = getInstrumentation().getContext().getResources();
mImageInputStream = res.openRawResource(mImageResourceId);
mXmlParser = res.getXml(mXmlResourceId);
}
}
| public void setUp() throws Exception {
try {
if (mImagePath != null) {
mImageInputStream = new FileInputStream(mImagePath);
mXmlInputStream = new FileInputStream(mXmlPath);
mXmlParser = Xml.newPullParser();
mXmlParser.setInput(new InputStreamReader(mXmlInputStream));
} else {
Resources res = getInstrumentation().getContext().getResources();
mImageInputStream = res.openRawResource(mImageResourceId);
mXmlParser = res.getXml(mXmlResourceId);
}
} catch (Exception e) {
throw new Exception(getImageTitle(), e);
}
}
|
diff --git a/App/src/com/dozuki/ifixit/ui/topic_view/TopicListFragment.java b/App/src/com/dozuki/ifixit/ui/topic_view/TopicListFragment.java
index 8a608bef..4a6bf4ee 100644
--- a/App/src/com/dozuki/ifixit/ui/topic_view/TopicListFragment.java
+++ b/App/src/com/dozuki/ifixit/ui/topic_view/TopicListFragment.java
@@ -1,151 +1,151 @@
package com.dozuki.ifixit.ui.topic_view;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.dozuki.ifixit.MainApplication;
import com.dozuki.ifixit.R;
import com.dozuki.ifixit.model.topic.TopicNode;
import com.dozuki.ifixit.model.topic.TopicSelectedListener;
import com.marczych.androidsectionheaders.SectionHeadersAdapter;
import com.marczych.androidsectionheaders.SectionListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class TopicListFragment extends SherlockFragment
implements TopicSelectedListener, OnItemClickListener {
private static final String CURRENT_TOPIC = "CURRENT_TOPIC";
private TopicSelectedListener topicSelectedListener;
private TopicNode mTopic;
private SectionHeadersAdapter mTopicAdapter;
private Context mContext;
private SectionListView mListView;
/**
* Required for restoring fragments
*/
public TopicListFragment() {}
public TopicListFragment(TopicNode topic) {
mTopic = topic;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mTopic = (TopicNode)savedInstanceState.getSerializable(CURRENT_TOPIC);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.topic_list_fragment, container, false);
mListView = (SectionListView)view.findViewById(R.id.topicList);
mListView.getListView().setOnItemClickListener(this);
setTopic(mTopic);
return view;
}
private void setupTopicAdapter() {
mTopicAdapter = new SectionHeadersAdapter();
ArrayList<TopicNode> generalInfo = new ArrayList<TopicNode>();
ArrayList<TopicNode> nonLeaves = new ArrayList<TopicNode>();
ArrayList<TopicNode> leaves = new ArrayList<TopicNode>();
TopicListAdapter adapter;
for (TopicNode topic : mTopic.getChildren()) {
if (topic.isLeaf()) {
leaves.add(topic);
} else {
nonLeaves.add(topic);
}
}
Comparator<TopicNode> comparator = new Comparator<TopicNode>() {
public int compare(TopicNode first, TopicNode second) {
- return first.getName().compareTo(second.getName());
+ return first.getName().compareToIgnoreCase(second.getName());
}
};
Collections.sort(nonLeaves, comparator);
Collections.sort(leaves, comparator);
if (!mTopic.isRoot() && !((TopicActivity)getActivity()).isDualPane()) {
generalInfo.add(new TopicNode(mTopic.getName()));
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.generalInformation), generalInfo);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (nonLeaves.size() > 0) {
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.categories), nonLeaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (leaves.size() > 0) {
MainApplication app = (MainApplication)getActivity().getApplication();
adapter = new TopicListAdapter(mContext, mContext.getString(
app.getSite().getObjectName()), leaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(CURRENT_TOPIC, mTopic);
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
mTopicAdapter.onItemClick(null, view, position, id);
}
public void onTopicSelected(TopicNode topic) {
topicSelectedListener.onTopicSelected(topic);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
topicSelectedListener = (TopicSelectedListener)activity;
mContext = (Context)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
" must implement TopicSelectedListener");
}
}
private void setTopic(TopicNode topic) {
mTopic = topic;
getSherlockActivity().setTitle(mTopic.getName().equals("ROOT") ? "" : mTopic.getName());
setupTopicAdapter();
mListView.setAdapter(mTopicAdapter);
}
}
| true | true | private void setupTopicAdapter() {
mTopicAdapter = new SectionHeadersAdapter();
ArrayList<TopicNode> generalInfo = new ArrayList<TopicNode>();
ArrayList<TopicNode> nonLeaves = new ArrayList<TopicNode>();
ArrayList<TopicNode> leaves = new ArrayList<TopicNode>();
TopicListAdapter adapter;
for (TopicNode topic : mTopic.getChildren()) {
if (topic.isLeaf()) {
leaves.add(topic);
} else {
nonLeaves.add(topic);
}
}
Comparator<TopicNode> comparator = new Comparator<TopicNode>() {
public int compare(TopicNode first, TopicNode second) {
return first.getName().compareTo(second.getName());
}
};
Collections.sort(nonLeaves, comparator);
Collections.sort(leaves, comparator);
if (!mTopic.isRoot() && !((TopicActivity)getActivity()).isDualPane()) {
generalInfo.add(new TopicNode(mTopic.getName()));
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.generalInformation), generalInfo);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (nonLeaves.size() > 0) {
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.categories), nonLeaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (leaves.size() > 0) {
MainApplication app = (MainApplication)getActivity().getApplication();
adapter = new TopicListAdapter(mContext, mContext.getString(
app.getSite().getObjectName()), leaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
}
| private void setupTopicAdapter() {
mTopicAdapter = new SectionHeadersAdapter();
ArrayList<TopicNode> generalInfo = new ArrayList<TopicNode>();
ArrayList<TopicNode> nonLeaves = new ArrayList<TopicNode>();
ArrayList<TopicNode> leaves = new ArrayList<TopicNode>();
TopicListAdapter adapter;
for (TopicNode topic : mTopic.getChildren()) {
if (topic.isLeaf()) {
leaves.add(topic);
} else {
nonLeaves.add(topic);
}
}
Comparator<TopicNode> comparator = new Comparator<TopicNode>() {
public int compare(TopicNode first, TopicNode second) {
return first.getName().compareToIgnoreCase(second.getName());
}
};
Collections.sort(nonLeaves, comparator);
Collections.sort(leaves, comparator);
if (!mTopic.isRoot() && !((TopicActivity)getActivity()).isDualPane()) {
generalInfo.add(new TopicNode(mTopic.getName()));
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.generalInformation), generalInfo);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (nonLeaves.size() > 0) {
adapter = new TopicListAdapter(mContext, mContext.getString(
R.string.categories), nonLeaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
if (leaves.size() > 0) {
MainApplication app = (MainApplication)getActivity().getApplication();
adapter = new TopicListAdapter(mContext, mContext.getString(
app.getSite().getObjectName()), leaves);
adapter.setTopicSelectedListener(this);
mTopicAdapter.addSection(adapter);
}
}
|
diff --git a/src/main/java/net/croxis/plugins/research/Research.java b/src/main/java/net/croxis/plugins/research/Research.java
index aed69ce..cbef71b 100644
--- a/src/main/java/net/croxis/plugins/research/Research.java
+++ b/src/main/java/net/croxis/plugins/research/Research.java
@@ -1,182 +1,182 @@
package net.croxis.plugins.research;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.PersistenceException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.Event.Type;
import org.bukkit.plugin.java.JavaPlugin;
public class Research extends JavaPlugin {
static TechManager techManager;
public boolean debug = false;
public HashSet<String> permissions = new HashSet<String>();
public HashSet<Integer> cantPlace = new HashSet<Integer>();
public HashSet<Integer> cantBreak = new HashSet<Integer>();
public HashSet<Integer> cantCraft = new HashSet<Integer>();
public HashSet<Integer> cantUse = new HashSet<Integer>();
public Logger logger;
private FileConfiguration techConfig = null;
//private File techConfigFile = new File(getDataFolder(), "tech.yml");
private File techConfigFile = null;
private RBlockListener blockListener = new RBlockListener();
private RPlayerListener playerListener = new RPlayerListener();
public void onDisable() {
// TODO: Place any custom disable code here.
System.out.println(this + " is now disabled!");
}
public void logDebug(String message){
if(debug)
logger.log(Level.INFO, "[Research - Debug] " + message);
}
public void logInfo(String message){
logger.log(Level.INFO, "[Research] " + message);
}
public void logWarning(String message){
logger.log(Level.WARNING, "[Research] " + message);
}
@SuppressWarnings("unchecked")
public void onEnable() {
logger = Logger.getLogger(JavaPlugin.class.getName());
techManager = new TechManager(this);
// Set up default systems
debug = this.getConfig().getBoolean("debug", false);
- permissions = (HashSet<String>) this.getConfig().getStringList("default.permissions");
- cantPlace = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantPlace");
- cantBreak = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantBreak");
- cantCraft = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantCraft");
- cantUse = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantUse");
+ permissions = new HashSet<String>(this.getConfig().getStringList("default.permissions"));
+ cantPlace = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantPlace"));
+ cantBreak = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantBreak"));
+ cantCraft = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantCraft"));
+ cantUse = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantUse"));
getConfig().options().copyDefaults(true);
saveConfig();
logInfo("Loaded default permissions. Now loading techs.");
// Load tech config
this.reloadTechConfig();
getTechConfig().options().copyDefaults(true);
saveTechConfig();
Set<String> techNames = techConfig.getKeys(false);
int i = 0;
for (String techName : techNames){
Tech tech = new Tech();
tech.name = techName;
if(!techConfig.contains(techName + ".cost"))
continue;
logInfo("Loading " + tech.name + " with recorded cost " + Integer.toString(techConfig.getInt(techName + ".cost")));
tech.cost = techConfig.getInt(techName + ".cost");
if(techConfig.contains(techName + ".permissions"))
tech.permissions = (HashSet<String>) techConfig.getStringList(techName + ".permissions");
if(techConfig.contains(techName + ".description"))
tech.description = techConfig.getString(techName + ".description");
if(techConfig.contains(techName + ".prereqs"))
tech.preReqs = (HashSet<String>) techConfig.getStringList(techName + ".prereqs");
if(techConfig.contains(techName + ".canPlace"))
tech.canPlace = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canPlace");
if(techConfig.contains(techName + ".canBreak"))
tech.canBreak = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canBreak");
if(techConfig.contains(techName + ".canCraft"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canCraft");
if(techConfig.contains(techName + ".canUse"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canUse");
techManager.techs.put(techName, tech);
i++;
}
logInfo(Integer.toString(i) + " techs loaded. Now linking tree.");
for (Tech tech : techManager.techs.values()){
// Check if it is a starting tech
//if(tech.preReqs.isEmpty()){
// tech.parents.add(techManager.techs.get("root"));
// techManager.techs.get("root").children.add(tech);
//} else {
for(String parentName : tech.preReqs){
if(techManager.techs.containsKey(parentName)){
tech.parents.add(techManager.techs.get(parentName));
techManager.techs.get(parentName).children.add(tech);
} else {
this.logWarning("Could not link " + tech.name + " with " + parentName + ". One of them is malformed!");
}
}
//}
}
logInfo("Tech tree linking complete. Mounting player database.");
setupDatabase();
logInfo("Database mounted. Setup complete.");
// This should be it. Permission setups should happen onPlayerJoin
this.getServer().getPluginManager().registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.CUSTOM_EVENT, new RInventoryListener(), Priority.Highest, this);
System.out.println(this + " is now enabled!");
}
public static TechManager getTechManager(){
return techManager;
}
public void reloadTechConfig() {
if (techConfigFile == null) {
techConfigFile = new File(getDataFolder(), "tech.yml");
}
techConfig = YamlConfiguration.loadConfiguration(techConfigFile);
// Look for defaults in the jar
InputStream defConfigStream = getResource("tech.yml");
if (defConfigStream != null) {
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
techConfig.setDefaults(defConfig);
}
}
public FileConfiguration getTechConfig() {
if (techConfig == null) {
reloadTechConfig();
}
return techConfig;
}
public void saveTechConfig() {
try {
techConfig.save(techConfigFile);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not save config to " + techConfigFile, ex);
}
}
private void setupDatabase() {
try {
getDatabase().find(SQLPlayer.class).findRowCount();
} catch (PersistenceException ex) {
System.out.println("Installing database for " + getDescription().getName() + " due to first time usage");
installDDL();
}
}
@Override
public List<Class<?>> getDatabaseClasses() {
List<Class<?>> list = new ArrayList<Class<?>>();
list.add(SQLPlayer.class);
return list;
}
}
| true | true | public void onEnable() {
logger = Logger.getLogger(JavaPlugin.class.getName());
techManager = new TechManager(this);
// Set up default systems
debug = this.getConfig().getBoolean("debug", false);
permissions = (HashSet<String>) this.getConfig().getStringList("default.permissions");
cantPlace = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantPlace");
cantBreak = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantBreak");
cantCraft = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantCraft");
cantUse = (HashSet<Integer>) this.getConfig().getIntegerList("default.cantUse");
getConfig().options().copyDefaults(true);
saveConfig();
logInfo("Loaded default permissions. Now loading techs.");
// Load tech config
this.reloadTechConfig();
getTechConfig().options().copyDefaults(true);
saveTechConfig();
Set<String> techNames = techConfig.getKeys(false);
int i = 0;
for (String techName : techNames){
Tech tech = new Tech();
tech.name = techName;
if(!techConfig.contains(techName + ".cost"))
continue;
logInfo("Loading " + tech.name + " with recorded cost " + Integer.toString(techConfig.getInt(techName + ".cost")));
tech.cost = techConfig.getInt(techName + ".cost");
if(techConfig.contains(techName + ".permissions"))
tech.permissions = (HashSet<String>) techConfig.getStringList(techName + ".permissions");
if(techConfig.contains(techName + ".description"))
tech.description = techConfig.getString(techName + ".description");
if(techConfig.contains(techName + ".prereqs"))
tech.preReqs = (HashSet<String>) techConfig.getStringList(techName + ".prereqs");
if(techConfig.contains(techName + ".canPlace"))
tech.canPlace = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canPlace");
if(techConfig.contains(techName + ".canBreak"))
tech.canBreak = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canBreak");
if(techConfig.contains(techName + ".canCraft"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canCraft");
if(techConfig.contains(techName + ".canUse"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canUse");
techManager.techs.put(techName, tech);
i++;
}
logInfo(Integer.toString(i) + " techs loaded. Now linking tree.");
for (Tech tech : techManager.techs.values()){
// Check if it is a starting tech
//if(tech.preReqs.isEmpty()){
// tech.parents.add(techManager.techs.get("root"));
// techManager.techs.get("root").children.add(tech);
//} else {
for(String parentName : tech.preReqs){
if(techManager.techs.containsKey(parentName)){
tech.parents.add(techManager.techs.get(parentName));
techManager.techs.get(parentName).children.add(tech);
} else {
this.logWarning("Could not link " + tech.name + " with " + parentName + ". One of them is malformed!");
}
}
//}
}
logInfo("Tech tree linking complete. Mounting player database.");
setupDatabase();
logInfo("Database mounted. Setup complete.");
// This should be it. Permission setups should happen onPlayerJoin
this.getServer().getPluginManager().registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.CUSTOM_EVENT, new RInventoryListener(), Priority.Highest, this);
System.out.println(this + " is now enabled!");
}
| public void onEnable() {
logger = Logger.getLogger(JavaPlugin.class.getName());
techManager = new TechManager(this);
// Set up default systems
debug = this.getConfig().getBoolean("debug", false);
permissions = new HashSet<String>(this.getConfig().getStringList("default.permissions"));
cantPlace = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantPlace"));
cantBreak = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantBreak"));
cantCraft = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantCraft"));
cantUse = new HashSet<Integer>( this.getConfig().getIntegerList("default.cantUse"));
getConfig().options().copyDefaults(true);
saveConfig();
logInfo("Loaded default permissions. Now loading techs.");
// Load tech config
this.reloadTechConfig();
getTechConfig().options().copyDefaults(true);
saveTechConfig();
Set<String> techNames = techConfig.getKeys(false);
int i = 0;
for (String techName : techNames){
Tech tech = new Tech();
tech.name = techName;
if(!techConfig.contains(techName + ".cost"))
continue;
logInfo("Loading " + tech.name + " with recorded cost " + Integer.toString(techConfig.getInt(techName + ".cost")));
tech.cost = techConfig.getInt(techName + ".cost");
if(techConfig.contains(techName + ".permissions"))
tech.permissions = (HashSet<String>) techConfig.getStringList(techName + ".permissions");
if(techConfig.contains(techName + ".description"))
tech.description = techConfig.getString(techName + ".description");
if(techConfig.contains(techName + ".prereqs"))
tech.preReqs = (HashSet<String>) techConfig.getStringList(techName + ".prereqs");
if(techConfig.contains(techName + ".canPlace"))
tech.canPlace = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canPlace");
if(techConfig.contains(techName + ".canBreak"))
tech.canBreak = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canBreak");
if(techConfig.contains(techName + ".canCraft"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canCraft");
if(techConfig.contains(techName + ".canUse"))
tech.canCraft = (HashSet<Integer>) techConfig.getIntegerList(techName + ".canUse");
techManager.techs.put(techName, tech);
i++;
}
logInfo(Integer.toString(i) + " techs loaded. Now linking tree.");
for (Tech tech : techManager.techs.values()){
// Check if it is a starting tech
//if(tech.preReqs.isEmpty()){
// tech.parents.add(techManager.techs.get("root"));
// techManager.techs.get("root").children.add(tech);
//} else {
for(String parentName : tech.preReqs){
if(techManager.techs.containsKey(parentName)){
tech.parents.add(techManager.techs.get(parentName));
techManager.techs.get(parentName).children.add(tech);
} else {
this.logWarning("Could not link " + tech.name + " with " + parentName + ". One of them is malformed!");
}
}
//}
}
logInfo("Tech tree linking complete. Mounting player database.");
setupDatabase();
logInfo("Database mounted. Setup complete.");
// This should be it. Permission setups should happen onPlayerJoin
this.getServer().getPluginManager().registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this);
this.getServer().getPluginManager().registerEvent(Type.CUSTOM_EVENT, new RInventoryListener(), Priority.Highest, this);
System.out.println(this + " is now enabled!");
}
|
diff --git a/library/src/org/holoeverywhere/app/TabSwipeActivity.java b/library/src/org/holoeverywhere/app/TabSwipeActivity.java
index dbb7f5ea..266abe0d 100644
--- a/library/src/org/holoeverywhere/app/TabSwipeActivity.java
+++ b/library/src/org/holoeverywhere/app/TabSwipeActivity.java
@@ -1,155 +1,151 @@
package org.holoeverywhere.app;
import org.holoeverywhere.R;
import org.holoeverywhere.widget.FrameLayout;
import android.os.Bundle;
/**
* This activity class implement tabs + swipe navigation pattern<br />
* <br />
* Part of HoloEverywhere
*/
public abstract class TabSwipeActivity extends Activity implements
TabSwipeInterface<TabSwipeFragment.TabInfo> {
public static class InnerFragment extends TabSwipeFragment {
private TabSwipeActivity mActivity;
private boolean mTabsWasHandled = false;
@Override
protected void onHandleTabs() {
mTabsWasHandled = true;
if (mActivity != null) {
mActivity.onHandleTabs();
}
}
public void setActivity(TabSwipeActivity activity) {
if (activity == null) {
return;
}
mActivity = activity;
if (mTabsWasHandled) {
mActivity.onHandleTabs();
}
}
}
private int mCustomLayout = -1;
private InnerFragment mFragment;
@Override
public TabSwipeFragment.TabInfo addTab(CharSequence title,
Class<? extends Fragment> fragmentClass) {
return mFragment.addTab(title, fragmentClass);
}
@Override
public TabSwipeFragment.TabInfo addTab(CharSequence title,
Class<? extends Fragment> fragmentClass, Bundle fragmentArguments) {
return mFragment.addTab(title, fragmentClass, fragmentArguments);
}
@Override
public TabSwipeFragment.TabInfo addTab(int title,
Class<? extends Fragment> fragmentClass) {
return mFragment.addTab(title, fragmentClass);
}
@Override
public TabSwipeFragment.TabInfo addTab(int title,
Class<? extends Fragment> fragmentClass, Bundle fragmentArguments) {
return mFragment.addTab(title, fragmentClass, fragmentArguments);
}
@Override
public TabSwipeFragment.TabInfo addTab(
TabSwipeFragment.TabInfo tabInfo) {
return mFragment.addTab(tabInfo);
}
@Override
public TabSwipeFragment.TabInfo addTab(
TabSwipeFragment.TabInfo tabInfo, int position) {
return mFragment.addTab(tabInfo, position);
}
@Override
public OnTabSelectedListener getOnTabSelectedListener() {
return mFragment.getOnTabSelectedListener();
}
@Override
public boolean isSmoothScroll() {
return mFragment.isSmoothScroll();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ FrameLayout layout = new FrameLayout(this);
+ layout.setId(R.id.contentPanel);
+ setContentView(layout);
mFragment = (InnerFragment) getSupportFragmentManager().findFragmentById(R.id.contentPanel);
if (mFragment == null) {
- mFragment = new InnerFragment();
+ getSupportFragmentManager().beginTransaction()
+ .replace(R.id.contentPanel, mFragment = new InnerFragment()).commit();
}
mFragment.setActivity(this);
if (mCustomLayout > 0) {
mFragment.setCustomLayout(mCustomLayout);
}
- if (mFragment.isDetached()) {
- FrameLayout layout = new FrameLayout(this);
- layout.setId(R.id.contentPanel);
- setContentView(layout);
- getSupportFragmentManager().beginTransaction()
- .replace(R.id.contentPanel, mFragment).commit();
- getSupportFragmentManager().executePendingTransactions();
- }
}
/**
* Add your tabs here
*/
protected abstract void onHandleTabs();
@Override
public void reloadTabs() {
mFragment.reloadTabs();
}
@Override
public void removeAllTabs() {
mFragment.removeAllTabs();
}
@Override
public TabSwipeFragment.TabInfo removeTab(int position) {
return mFragment.removeTab(position);
}
@Override
public TabSwipeFragment.TabInfo removeTab(
TabSwipeFragment.TabInfo tabInfo) {
return mFragment.removeTab(tabInfo);
}
@Override
public void setCurrentTab(int position) {
mFragment.setCurrentTab(position);
}
@Override
public void setCustomLayout(int customLayout) {
mCustomLayout = customLayout;
}
@Override
public void setOnTabSelectedListener(OnTabSelectedListener onTabSelectedListener) {
mFragment.setOnTabSelectedListener(onTabSelectedListener);
}
@Override
public void setSmoothScroll(boolean smoothScroll) {
mFragment.setSmoothScroll(smoothScroll);
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFragment = (InnerFragment) getSupportFragmentManager().findFragmentById(R.id.contentPanel);
if (mFragment == null) {
mFragment = new InnerFragment();
}
mFragment.setActivity(this);
if (mCustomLayout > 0) {
mFragment.setCustomLayout(mCustomLayout);
}
if (mFragment.isDetached()) {
FrameLayout layout = new FrameLayout(this);
layout.setId(R.id.contentPanel);
setContentView(layout);
getSupportFragmentManager().beginTransaction()
.replace(R.id.contentPanel, mFragment).commit();
getSupportFragmentManager().executePendingTransactions();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout layout = new FrameLayout(this);
layout.setId(R.id.contentPanel);
setContentView(layout);
mFragment = (InnerFragment) getSupportFragmentManager().findFragmentById(R.id.contentPanel);
if (mFragment == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.contentPanel, mFragment = new InnerFragment()).commit();
}
mFragment.setActivity(this);
if (mCustomLayout > 0) {
mFragment.setCustomLayout(mCustomLayout);
}
}
|
diff --git a/main/src/cgeo/geocaching/export/GpxSerializer.java b/main/src/cgeo/geocaching/export/GpxSerializer.java
index ecc687f23..2afed44af 100644
--- a/main/src/cgeo/geocaching/export/GpxSerializer.java
+++ b/main/src/cgeo/geocaching/export/GpxSerializer.java
@@ -1,306 +1,311 @@
package cgeo.geocaching.export;
import cgeo.geocaching.DataStore;
import cgeo.geocaching.Geocache;
import cgeo.geocaching.LogEntry;
import cgeo.geocaching.Trackable;
import cgeo.geocaching.Waypoint;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.utils.TextUtils;
import cgeo.geocaching.utils.XmlUtils;
import cgeo.org.kxml2.io.KXmlSerializer;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;
public final class GpxSerializer {
private static final FastDateFormat dateFormatZ = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
public static final String PREFIX_XSI = "http://www.w3.org/2001/XMLSchema-instance";
public static final String PREFIX_GPX = "http://www.topografix.com/GPX/1/0";
public static final String PREFIX_GROUNDSPEAK = "http://www.groundspeak.com/cache/1/0";
public static final String PREFIX_GSAK = "http://www.gsak.net/xmlv1/4";
public static final String PREFIX_CGEO = "http://www.cgeo.org/wptext/1/0";
/**
* During the export, only this number of geocaches is fully loaded into memory.
*/
public static final int CACHES_PER_BATCH = 100;
/**
* counter for exported caches, used for progress reporting
*/
private int countExported;
private ProgressListener progressListener;
private final XmlSerializer gpx = new KXmlSerializer();
protected static interface ProgressListener {
void publishProgress(int countExported);
}
public void writeGPX(List<String> allGeocodesIn, Writer writer, final ProgressListener progressListener) throws IOException {
// create a copy of the geocode list, as we need to modify it, but it might be immutable
final ArrayList<String> allGeocodes = new ArrayList<String>(allGeocodesIn);
this.progressListener = progressListener;
gpx.setOutput(writer);
gpx.startDocument(CharEncoding.UTF_8, true);
gpx.setPrefix("", PREFIX_GPX);
gpx.setPrefix("xsi", PREFIX_XSI);
gpx.setPrefix("groundspeak", PREFIX_GROUNDSPEAK);
gpx.setPrefix("gsak", PREFIX_GSAK);
gpx.setPrefix("cgeo", PREFIX_CGEO);
gpx.startTag(PREFIX_GPX, "gpx");
gpx.attribute("", "version", "1.0");
gpx.attribute("", "creator", "c:geo - http://www.cgeo.org/");
gpx.attribute(PREFIX_XSI, "schemaLocation",
PREFIX_GPX + " http://www.topografix.com/GPX/1/0/gpx.xsd " +
PREFIX_GROUNDSPEAK + " http://www.groundspeak.com/cache/1/0/1/cache.xsd " +
PREFIX_GSAK + " http://www.gsak.net/xmlv1/4/gsak.xsd");
// Split the overall set of geocodes into small chunks. That is a compromise between memory efficiency (because
// we don't load all caches fully into memory) and speed (because we don't query each cache separately).
while (!allGeocodes.isEmpty()) {
final List<String> batch = allGeocodes.subList(0, Math.min(CACHES_PER_BATCH, allGeocodes.size()));
exportBatch(gpx, batch);
batch.clear();
}
gpx.endTag(PREFIX_GPX, "gpx");
gpx.endDocument();
}
private void exportBatch(final XmlSerializer gpx, Collection<String> geocodesOfBatch) throws IOException {
final Set<Geocache> caches = DataStore.loadCaches(geocodesOfBatch, LoadFlags.LOAD_ALL_DB_ONLY);
for (final Geocache cache : caches) {
+ final Geopoint coords = cache != null ? cache.getCoords() : null;
+ if (coords == null) {
+ // Export would be invalid without coordinates.
+ continue;
+ }
gpx.startTag(PREFIX_GPX, "wpt");
- gpx.attribute("", "lat", Double.toString(cache.getCoords().getLatitude()));
- gpx.attribute("", "lon", Double.toString(cache.getCoords().getLongitude()));
+ gpx.attribute("", "lat", Double.toString(coords.getLatitude()));
+ gpx.attribute("", "lon", Double.toString(coords.getLongitude()));
final Date hiddenDate = cache.getHiddenDate();
if (hiddenDate != null) {
XmlUtils.simpleText(gpx, PREFIX_GPX, "time", dateFormatZ.format(hiddenDate));
}
XmlUtils.multipleTexts(gpx, PREFIX_GPX,
"name", cache.getGeocode(),
"desc", cache.getName(),
"url", cache.getUrl(),
"urlname", cache.getName(),
"sym", cache.isFound() ? "Geocache Found" : "Geocache",
"type", "Geocache|" + cache.getType().pattern);
gpx.startTag(PREFIX_GROUNDSPEAK, "cache");
gpx.attribute("", "id", cache.getCacheId());
gpx.attribute("", "available", !cache.isDisabled() ? "True" : "False");
gpx.attribute("", "archived", cache.isArchived() ? "True" : "False");
XmlUtils.multipleTexts(gpx, PREFIX_GROUNDSPEAK,
"name", cache.getName(),
"placed_by", cache.getOwnerDisplayName(),
"owner", cache.getOwnerUserId(),
"type", cache.getType().pattern,
"container", cache.getSize().id,
"difficulty", Float.toString(cache.getDifficulty()),
"terrain", Float.toString(cache.getTerrain()),
"country", cache.getLocation(),
"state", "",
"encoded_hints", cache.getHint());
writeAttributes(cache);
gpx.startTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getShortDescription()) ? "True" : "False");
gpx.text(cache.getShortDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.startTag(PREFIX_GROUNDSPEAK, "long_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getDescription()) ? "True" : "False");
gpx.text(cache.getDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "long_description");
writeLogs(cache);
writeTravelBugs(cache);
gpx.endTag(PREFIX_GROUNDSPEAK, "cache");
gpx.endTag(PREFIX_GPX, "wpt");
writeWaypoints(cache);
countExported++;
if (progressListener != null) {
progressListener.publishProgress(countExported);
}
}
}
private void writeWaypoints(final Geocache cache) throws IOException {
final List<Waypoint> waypoints = cache.getWaypoints();
final List<Waypoint> ownWaypoints = new ArrayList<Waypoint>(waypoints.size());
final List<Waypoint> originWaypoints = new ArrayList<Waypoint>(waypoints.size());
int maxPrefix = 0;
for (final Waypoint wp : cache.getWaypoints()) {
// Retrieve numerical prefixes to have a basis for assigning prefixes to own waypoints
final String prefix = wp.getPrefix();
if (StringUtils.isNotBlank(prefix)) {
try {
final int numericPrefix = Integer.parseInt(prefix);
maxPrefix = Math.max(numericPrefix, maxPrefix);
} catch (final NumberFormatException ex) {
// ignore non numeric prefix, as it should be unique in the list of non-own waypoints already
}
}
if (wp.isUserDefined()) {
ownWaypoints.add(wp);
} else {
originWaypoints.add(wp);
}
}
for (final Waypoint wp : originWaypoints) {
writeCacheWaypoint(wp);
}
// Prefixes must be unique. There use numeric strings as prefixes in OWN waypoints where they are missing
for (final Waypoint wp : ownWaypoints) {
if (StringUtils.isBlank(wp.getPrefix()) || StringUtils.equalsIgnoreCase(Waypoint.PREFIX_OWN, wp.getPrefix())) {
maxPrefix++;
wp.setPrefix(StringUtils.leftPad(String.valueOf(maxPrefix), 2, '0'));
}
writeCacheWaypoint(wp);
}
}
/**
* Writes one waypoint entry for cache waypoint.
*
* @param cache
* The
* @param wp
* @param prefix
* @throws IOException
*/
private void writeCacheWaypoint(final Waypoint wp) throws IOException {
final Geopoint coords = wp.getCoords();
// TODO: create some extension to GPX to include waypoint without coords
if (coords != null) {
gpx.startTag(PREFIX_GPX, "wpt");
gpx.attribute("", "lat", Double.toString(coords.getLatitude()));
gpx.attribute("", "lon", Double.toString(coords.getLongitude()));
XmlUtils.multipleTexts(gpx, PREFIX_GPX,
"name", wp.getGpxId(),
"cmt", wp.getNote(),
"desc", wp.getName(),
"sym", wp.getWaypointType().toString(), //TODO: Correct identifier string
"type", "Waypoint|" + wp.getWaypointType().toString()); //TODO: Correct identifier string
// add parent reference the GSAK-way
gpx.startTag(PREFIX_GSAK, "wptExtension");
gpx.startTag(PREFIX_GSAK, "Parent");
gpx.text(wp.getGeocode());
gpx.endTag(PREFIX_GSAK, "Parent");
gpx.endTag(PREFIX_GSAK, "wptExtension");
if (wp.isVisited()) {
gpx.startTag(PREFIX_CGEO, "visited");
gpx.text("true");
gpx.endTag(PREFIX_CGEO, "visited");
}
if (wp.isUserDefined()) {
gpx.startTag(PREFIX_CGEO, "userdefined");
gpx.text("true");
gpx.endTag(PREFIX_CGEO, "userdefined");
}
gpx.endTag(PREFIX_GPX, "wpt");
}
}
private void writeLogs(final Geocache cache) throws IOException {
if (cache.getLogs().isEmpty()) {
return;
}
gpx.startTag(PREFIX_GROUNDSPEAK, "logs");
for (final LogEntry log : cache.getLogs()) {
gpx.startTag(PREFIX_GROUNDSPEAK, "log");
gpx.attribute("", "id", Integer.toString(log.id));
XmlUtils.multipleTexts(gpx, PREFIX_GROUNDSPEAK,
"date", dateFormatZ.format(new Date(log.date)),
"type", log.type.type);
gpx.startTag(PREFIX_GROUNDSPEAK, "finder");
gpx.attribute("", "id", "");
gpx.text(log.author);
gpx.endTag(PREFIX_GROUNDSPEAK, "finder");
gpx.startTag(PREFIX_GROUNDSPEAK, "text");
gpx.attribute("", "encoded", "False");
gpx.text(log.log);
gpx.endTag(PREFIX_GROUNDSPEAK, "text");
gpx.endTag(PREFIX_GROUNDSPEAK, "log");
}
gpx.endTag(PREFIX_GROUNDSPEAK, "logs");
}
private void writeTravelBugs(final Geocache cache) throws IOException {
List<Trackable> inventory = cache.getInventory();
if (CollectionUtils.isEmpty(inventory)) {
return;
}
gpx.startTag(PREFIX_GROUNDSPEAK, "travelbugs");
for (final Trackable trackable : inventory) {
gpx.startTag(PREFIX_GROUNDSPEAK, "travelbug");
// in most cases the geocode will be empty (only the guid is known). those travel bugs cannot be imported again!
gpx.attribute("", "ref", trackable.getGeocode());
XmlUtils.simpleText(gpx, PREFIX_GROUNDSPEAK, "name", trackable.getName());
gpx.endTag(PREFIX_GROUNDSPEAK, "travelbug");
}
gpx.endTag(PREFIX_GROUNDSPEAK, "travelbugs");
}
private void writeAttributes(final Geocache cache) throws IOException {
if (cache.getAttributes().isEmpty()) {
return;
}
//TODO: Attribute conversion required: English verbose name, gpx-id
gpx.startTag(PREFIX_GROUNDSPEAK, "attributes");
for (final String attribute : cache.getAttributes()) {
final CacheAttribute attr = CacheAttribute.getByRawName(CacheAttribute.trimAttributeName(attribute));
if (attr == null) {
continue;
}
final boolean enabled = CacheAttribute.isEnabled(attribute);
gpx.startTag(PREFIX_GROUNDSPEAK, "attribute");
gpx.attribute("", "id", Integer.toString(attr.gcid));
gpx.attribute("", "inc", enabled ? "1" : "0");
gpx.text(attr.getL10n(enabled));
gpx.endTag(PREFIX_GROUNDSPEAK, "attribute");
}
gpx.endTag(PREFIX_GROUNDSPEAK, "attributes");
}
}
| false | true | private void exportBatch(final XmlSerializer gpx, Collection<String> geocodesOfBatch) throws IOException {
final Set<Geocache> caches = DataStore.loadCaches(geocodesOfBatch, LoadFlags.LOAD_ALL_DB_ONLY);
for (final Geocache cache : caches) {
gpx.startTag(PREFIX_GPX, "wpt");
gpx.attribute("", "lat", Double.toString(cache.getCoords().getLatitude()));
gpx.attribute("", "lon", Double.toString(cache.getCoords().getLongitude()));
final Date hiddenDate = cache.getHiddenDate();
if (hiddenDate != null) {
XmlUtils.simpleText(gpx, PREFIX_GPX, "time", dateFormatZ.format(hiddenDate));
}
XmlUtils.multipleTexts(gpx, PREFIX_GPX,
"name", cache.getGeocode(),
"desc", cache.getName(),
"url", cache.getUrl(),
"urlname", cache.getName(),
"sym", cache.isFound() ? "Geocache Found" : "Geocache",
"type", "Geocache|" + cache.getType().pattern);
gpx.startTag(PREFIX_GROUNDSPEAK, "cache");
gpx.attribute("", "id", cache.getCacheId());
gpx.attribute("", "available", !cache.isDisabled() ? "True" : "False");
gpx.attribute("", "archived", cache.isArchived() ? "True" : "False");
XmlUtils.multipleTexts(gpx, PREFIX_GROUNDSPEAK,
"name", cache.getName(),
"placed_by", cache.getOwnerDisplayName(),
"owner", cache.getOwnerUserId(),
"type", cache.getType().pattern,
"container", cache.getSize().id,
"difficulty", Float.toString(cache.getDifficulty()),
"terrain", Float.toString(cache.getTerrain()),
"country", cache.getLocation(),
"state", "",
"encoded_hints", cache.getHint());
writeAttributes(cache);
gpx.startTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getShortDescription()) ? "True" : "False");
gpx.text(cache.getShortDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.startTag(PREFIX_GROUNDSPEAK, "long_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getDescription()) ? "True" : "False");
gpx.text(cache.getDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "long_description");
writeLogs(cache);
writeTravelBugs(cache);
gpx.endTag(PREFIX_GROUNDSPEAK, "cache");
gpx.endTag(PREFIX_GPX, "wpt");
writeWaypoints(cache);
countExported++;
if (progressListener != null) {
progressListener.publishProgress(countExported);
}
}
}
| private void exportBatch(final XmlSerializer gpx, Collection<String> geocodesOfBatch) throws IOException {
final Set<Geocache> caches = DataStore.loadCaches(geocodesOfBatch, LoadFlags.LOAD_ALL_DB_ONLY);
for (final Geocache cache : caches) {
final Geopoint coords = cache != null ? cache.getCoords() : null;
if (coords == null) {
// Export would be invalid without coordinates.
continue;
}
gpx.startTag(PREFIX_GPX, "wpt");
gpx.attribute("", "lat", Double.toString(coords.getLatitude()));
gpx.attribute("", "lon", Double.toString(coords.getLongitude()));
final Date hiddenDate = cache.getHiddenDate();
if (hiddenDate != null) {
XmlUtils.simpleText(gpx, PREFIX_GPX, "time", dateFormatZ.format(hiddenDate));
}
XmlUtils.multipleTexts(gpx, PREFIX_GPX,
"name", cache.getGeocode(),
"desc", cache.getName(),
"url", cache.getUrl(),
"urlname", cache.getName(),
"sym", cache.isFound() ? "Geocache Found" : "Geocache",
"type", "Geocache|" + cache.getType().pattern);
gpx.startTag(PREFIX_GROUNDSPEAK, "cache");
gpx.attribute("", "id", cache.getCacheId());
gpx.attribute("", "available", !cache.isDisabled() ? "True" : "False");
gpx.attribute("", "archived", cache.isArchived() ? "True" : "False");
XmlUtils.multipleTexts(gpx, PREFIX_GROUNDSPEAK,
"name", cache.getName(),
"placed_by", cache.getOwnerDisplayName(),
"owner", cache.getOwnerUserId(),
"type", cache.getType().pattern,
"container", cache.getSize().id,
"difficulty", Float.toString(cache.getDifficulty()),
"terrain", Float.toString(cache.getTerrain()),
"country", cache.getLocation(),
"state", "",
"encoded_hints", cache.getHint());
writeAttributes(cache);
gpx.startTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getShortDescription()) ? "True" : "False");
gpx.text(cache.getShortDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "short_description");
gpx.startTag(PREFIX_GROUNDSPEAK, "long_description");
gpx.attribute("", "html", TextUtils.containsHtml(cache.getDescription()) ? "True" : "False");
gpx.text(cache.getDescription());
gpx.endTag(PREFIX_GROUNDSPEAK, "long_description");
writeLogs(cache);
writeTravelBugs(cache);
gpx.endTag(PREFIX_GROUNDSPEAK, "cache");
gpx.endTag(PREFIX_GPX, "wpt");
writeWaypoints(cache);
countExported++;
if (progressListener != null) {
progressListener.publishProgress(countExported);
}
}
}
|
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
index 0cfb305bd..491250b52 100644
--- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
+++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
@@ -1,1105 +1,1105 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.HasArrayBufferView;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.google.gwt.core.client.GWT;
import com.google.gwt.typedarrays.client.Float32Array;
import com.google.gwt.typedarrays.client.Int16Array;
import com.google.gwt.typedarrays.client.Int32Array;
import com.google.gwt.typedarrays.client.Uint8Array;
import com.google.gwt.webgl.client.WebGLActiveInfo;
import com.google.gwt.webgl.client.WebGLBuffer;
import com.google.gwt.webgl.client.WebGLFramebuffer;
import com.google.gwt.webgl.client.WebGLProgram;
import com.google.gwt.webgl.client.WebGLRenderbuffer;
import com.google.gwt.webgl.client.WebGLRenderingContext;
import com.google.gwt.webgl.client.WebGLShader;
import com.google.gwt.webgl.client.WebGLTexture;
import com.google.gwt.webgl.client.WebGLUniformLocation;
public class GwtGL20 implements GL20 {
final Map<Integer, WebGLProgram> programs = new HashMap<Integer, WebGLProgram>();
int nextProgramId = 1;
final Map<Integer, WebGLShader> shaders = new HashMap<Integer, WebGLShader>();
int nextShaderId = 1;
final Map<Integer, WebGLBuffer> buffers = new HashMap<Integer, WebGLBuffer>();
int nextBufferId = 1;
final Map<Integer, WebGLFramebuffer> frameBuffers = new HashMap<Integer, WebGLFramebuffer>();
int nextFrameBufferId = 1;
final Map<Integer, WebGLRenderbuffer> renderBuffers = new HashMap<Integer, WebGLRenderbuffer>();
int nextRenderBufferId = 1;
final Map<Integer, WebGLTexture> textures = new HashMap<Integer, WebGLTexture>();
int nextTextureId = 1;
final Map<Integer, Map<Integer, WebGLUniformLocation>> uniforms = new HashMap<Integer, Map<Integer, WebGLUniformLocation>>();
int nextUniformId = 1;
int currProgram = 0;
Float32Array floatBuffer = Float32Array.create(2000 * 20);
Int16Array shortBuffer = Int16Array.create(2000 * 6);
final WebGLRenderingContext gl;
protected GwtGL20 (WebGLRenderingContext gl) {
this.gl = gl;
this.gl.pixelStorei(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
}
private void ensureCapacity (FloatBuffer buffer) {
if (buffer.remaining() > floatBuffer.getLength()) {
floatBuffer = Float32Array.create(buffer.remaining());
}
}
private void ensureCapacity (ShortBuffer buffer) {
if (buffer.remaining() > shortBuffer.getLength()) {
shortBuffer = Int16Array.create(buffer.remaining());
}
}
public Float32Array copy (FloatBuffer buffer) {
if (GWT.isProdMode()) {
return ((Float32Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining());
} else {
ensureCapacity(buffer);
float[] array = buffer.array();
for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) {
floatBuffer.set(j, array[i]);
}
return floatBuffer.subarray(0, buffer.remaining());
}
}
public Int16Array copy (ShortBuffer buffer) {
if (GWT.isProdMode()) {
return ((Int16Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining());
} else {
ensureCapacity(buffer);
short[] array = buffer.array();
for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) {
shortBuffer.set(j, array[i]);
}
return shortBuffer.subarray(0, buffer.remaining());
}
}
private int allocateUniformLocationId (int program, WebGLUniformLocation location) {
Map<Integer, WebGLUniformLocation> progUniforms = uniforms.get(program);
if (progUniforms == null) {
progUniforms = new HashMap<Integer, WebGLUniformLocation>();
uniforms.put(program, progUniforms);
}
// FIXME check if uniform already stored.
int id = nextUniformId++;
progUniforms.put(id, location);
return id;
}
private WebGLUniformLocation getUniformLocation (int location) {
return uniforms.get(currProgram).get(location);
}
private int allocateShaderId (WebGLShader shader) {
int id = nextShaderId++;
shaders.put(id, shader);
return id;
}
private void deallocateShaderId (int id) {
shaders.remove(id);
}
private int allocateProgramId (WebGLProgram program) {
int id = nextProgramId++;
programs.put(id, program);
return id;
}
private void deallocateProgramId (int id) {
uniforms.remove(id);
programs.remove(id);
}
private int allocateBufferId (WebGLBuffer buffer) {
int id = nextBufferId++;
buffers.put(id, buffer);
return id;
}
private void deallocateBufferId (int id) {
buffers.remove(id);
}
private int allocateFrameBufferId (WebGLFramebuffer frameBuffer) {
int id = nextBufferId++;
frameBuffers.put(id, frameBuffer);
return id;
}
private void deallocateFrameBufferId (int id) {
frameBuffers.remove(id);
}
private int allocateRenderBufferId (WebGLRenderbuffer renderBuffer) {
int id = nextRenderBufferId++;
renderBuffers.put(id, renderBuffer);
return id;
}
private void deallocateRenderBufferId (int id) {
renderBuffers.remove(id);
}
private int allocateTextureId (WebGLTexture texture) {
int id = nextTextureId++;
textures.put(id, texture);
return id;
}
private void deallocateTextureId (int id) {
textures.remove(id);
}
@Override
public void glActiveTexture (int texture) {
gl.activeTexture(texture);
}
@Override
public void glBindTexture (int target, int texture) {
gl.bindTexture(target, textures.get(texture));
}
@Override
public void glBlendFunc (int sfactor, int dfactor) {
gl.blendFunc(sfactor, dfactor);
}
@Override
public void glClear (int mask) {
gl.clear(mask);
}
@Override
public void glClearColor (float red, float green, float blue, float alpha) {
gl.clearColor(red, green, blue, alpha);
}
@Override
public void glClearDepthf (float depth) {
gl.clearDepth(depth);
}
@Override
public void glClearStencil (int s) {
gl.clearStencil(s);
}
@Override
public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) {
gl.colorMask(red, green, blue, alpha);
}
@Override
public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border,
int imageSize, Buffer data) {
throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend");
}
@Override
public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format,
int imageSize, Buffer data) {
throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend");
}
@Override
public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) {
gl.copyTexImage2D(target, level, internalformat, x, y, width, height, border);
}
@Override
public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
gl.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
}
@Override
public void glCullFace (int mode) {
gl.cullFace(mode);
}
@Override
public void glDeleteTextures (int n, IntBuffer textures) {
for (int i = 0; i < n; i++) {
int id = textures.get();
WebGLTexture texture = this.textures.get(id);
deallocateTextureId(id);
gl.deleteTexture(texture);
}
}
@Override
public void glDepthFunc (int func) {
gl.depthFunc(func);
}
@Override
public void glDepthMask (boolean flag) {
gl.depthMask(flag);
}
@Override
public void glDepthRangef (float zNear, float zFar) {
gl.depthRange(zNear, zFar);
}
@Override
public void glDisable (int cap) {
gl.disable(cap);
}
@Override
public void glDrawArrays (int mode, int first, int count) {
gl.drawArrays(mode, first, count);
}
@Override
public void glDrawElements (int mode, int count, int type, Buffer indices) {
gl.drawElements(mode, count, type, indices.position()); // FIXME this is assuming WebGL supports client side buffers...
}
@Override
public void glEnable (int cap) {
gl.enable(cap);
}
@Override
public void glFinish () {
gl.finish();
}
@Override
public void glFlush () {
gl.flush();
}
@Override
public void glFrontFace (int mode) {
gl.frontFace(mode);
}
@Override
public void glGenTextures (int n, IntBuffer textures) {
WebGLTexture texture = gl.createTexture();
int id = allocateTextureId(texture);
textures.put(id);
}
@Override
public int glGetError () {
return gl.getError();
}
@Override
public void glGetIntegerv (int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("glGetInteger not supported by GWT WebGL backend");
}
@Override
public String glGetString (int name) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glHint (int target, int mode) {
gl.hint(target, mode);
}
@Override
public void glLineWidth (float width) {
gl.lineWidth(width);
}
@Override
public void glPixelStorei (int pname, int param) {
gl.pixelStorei(pname, param);
}
@Override
public void glPolygonOffset (float factor, float units) {
gl.polygonOffset(factor, units);
}
@Override
public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) {
- throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported.");
+ throw new GdxRuntimeException("Only format RGBA and type UNSIGNED_BYTE are currently supported for glReadPixels(...).");
}
if (!(pixels instanceof ByteBuffer)) {
- throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer.");
+ throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer for glReadPixels(...).");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
@Override
public void glScissor (int x, int y, int width, int height) {
gl.scissor(x, y, width, height);
}
@Override
public void glStencilFunc (int func, int ref, int mask) {
gl.stencilFunc(func, ref, mask);
}
@Override
public void glStencilMask (int mask) {
gl.stencilMask(mask);
}
@Override
public void glStencilOp (int fail, int zfail, int zpass) {
gl.stencilOp(fail, zfail, zpass);
}
@Override
public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type,
Buffer pixels) {
Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0));
gl.texImage2D(target, level, internalformat, format, type, pixmap.getCanvasElement());
}
@Override
public void glTexParameterf (int target, int pname, float param) {
gl.texParameterf(target, pname, param);
}
@Override
public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type,
Buffer pixels) {
Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0));
gl.texSubImage2D(target, level, xoffset, yoffset, width, height, pixmap.getCanvasElement());
}
@Override
public void glViewport (int x, int y, int width, int height) {
gl.viewport(x, y, width, height);
}
@Override
public void glAttachShader (int program, int shader) {
WebGLProgram glProgram = programs.get(program);
WebGLShader glShader = shaders.get(shader);
gl.attachShader(glProgram, glShader);
}
@Override
public void glBindAttribLocation (int program, int index, String name) {
WebGLProgram glProgram = programs.get(program);
gl.bindAttribLocation(glProgram, index, name);
}
@Override
public void glBindBuffer (int target, int buffer) {
gl.bindBuffer(target, buffers.get(buffer));
}
@Override
public void glBindFramebuffer (int target, int framebuffer) {
gl.bindFramebuffer(target, frameBuffers.get(framebuffer));
}
@Override
public void glBindRenderbuffer (int target, int renderbuffer) {
gl.bindRenderbuffer(target, renderBuffers.get(renderbuffer));
}
@Override
public void glBlendColor (float red, float green, float blue, float alpha) {
gl.blendColor(red, green, blue, alpha);
}
@Override
public void glBlendEquation (int mode) {
gl.blendEquation(mode);
}
@Override
public void glBlendEquationSeparate (int modeRGB, int modeAlpha) {
gl.blendEquationSeparate(modeRGB, modeAlpha);
}
@Override
public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void glBufferData (int target, int size, Buffer data, int usage) {
if (data instanceof FloatBuffer) {
gl.bufferData(target, copy((FloatBuffer)data), usage);
} else if (data instanceof ShortBuffer) {
gl.bufferData(target, copy((ShortBuffer)data), usage);
} else {
throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment");
}
}
@Override
public void glBufferSubData (int target, int offset, int size, Buffer data) {
if (data instanceof FloatBuffer) {
gl.bufferSubData(target, offset, copy((FloatBuffer)data));
} else if (data instanceof ShortBuffer) {
gl.bufferSubData(target, offset, copy((ShortBuffer)data));
} else {
throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment");
}
}
@Override
public int glCheckFramebufferStatus (int target) {
return gl.checkFramebufferStatus(target);
}
@Override
public void glCompileShader (int shader) {
WebGLShader glShader = shaders.get(shader);
gl.compileShader(glShader);
}
@Override
public int glCreateProgram () {
WebGLProgram program = gl.createProgram();
return allocateProgramId(program);
}
@Override
public int glCreateShader (int type) {
WebGLShader shader = gl.createShader(type);
return allocateShaderId(shader);
}
@Override
public void glDeleteBuffers (int n, IntBuffer buffers) {
for (int i = 0; i < n; i++) {
int id = buffers.get();
WebGLBuffer buffer = this.buffers.get(id);
deallocateBufferId(id);
gl.deleteBuffer(buffer);
}
}
@Override
public void glDeleteFramebuffers (int n, IntBuffer framebuffers) {
for (int i = 0; i < n; i++) {
int id = framebuffers.get();
WebGLFramebuffer fb = this.frameBuffers.get(id);
deallocateFrameBufferId(id);
gl.deleteFramebuffer(fb);
}
}
@Override
public void glDeleteProgram (int program) {
WebGLProgram prog = programs.get(program);
deallocateProgramId(program);
gl.deleteProgram(prog);
}
@Override
public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) {
for (int i = 0; i < n; i++) {
int id = renderbuffers.get();
WebGLRenderbuffer rb = this.renderBuffers.get(id);
deallocateRenderBufferId(id);
gl.deleteRenderbuffer(rb);
}
}
@Override
public void glDeleteShader (int shader) {
WebGLShader sh = shaders.get(shader);
deallocateShaderId(shader);
gl.deleteShader(sh);
}
@Override
public void glDetachShader (int program, int shader) {
gl.detachShader(programs.get(program), shaders.get(shader));
}
@Override
public void glDisableVertexAttribArray (int index) {
gl.disableVertexAttribArray(index);
}
@Override
public void glDrawElements (int mode, int count, int type, int indices) {
gl.drawElements(mode, count, type, indices);
}
@Override
public void glEnableVertexAttribArray (int index) {
gl.enableVertexAttribArray(index);
}
@Override
public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) {
gl.framebufferRenderbuffer(target, attachment, renderbuffertarget, renderBuffers.get(renderbuffer));
}
@Override
public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) {
gl.framebufferTexture2D(target, attachment, textarget, textures.get(texture), level);
}
@Override
public void glGenBuffers (int n, IntBuffer buffers) {
for (int i = 0; i < n; i++) {
WebGLBuffer buffer = gl.createBuffer();
int id = allocateBufferId(buffer);
buffers.put(id);
}
}
@Override
public void glGenerateMipmap (int target) {
gl.generateMipmap(target);
}
@Override
public void glGenFramebuffers (int n, IntBuffer framebuffers) {
for (int i = 0; i < n; i++) {
WebGLFramebuffer fb = gl.createFramebuffer();
int id = allocateFrameBufferId(fb);
framebuffers.put(id);
}
}
@Override
public void glGenRenderbuffers (int n, IntBuffer renderbuffers) {
for (int i = 0; i < n; i++) {
WebGLRenderbuffer rb = gl.createRenderbuffer();
int id = allocateRenderBufferId(rb);
renderbuffers.put(id);
}
}
@Override
public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) {
WebGLActiveInfo activeAttrib = gl.getActiveAttrib(programs.get(program), index);
size.put(activeAttrib.getSize());
((IntBuffer)type).put(activeAttrib.getType());
return activeAttrib.getName();
}
@Override
public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) {
WebGLActiveInfo activeUniform = gl.getActiveUniform(programs.get(program), index);
size.put(activeUniform.getSize());
((IntBuffer)type).put(activeUniform.getType());
return activeUniform.getName();
}
@Override
public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public int glGetAttribLocation (int program, String name) {
WebGLProgram prog = programs.get(program);
return gl.getAttribLocation(prog, name);
}
@Override
public void glGetBooleanv (int pname, Buffer params) {
throw new GdxRuntimeException("glGetBoolean not supported by GWT WebGL backend");
}
@Override
public void glGetBufferParameteriv (int target, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetFloatv (int pname, FloatBuffer params) {
throw new GdxRuntimeException("glGetFloat not supported by GWT WebGL backend");
}
@Override
public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetProgramiv (int program, int pname, IntBuffer params) {
if (pname == GL20.GL_DELETE_STATUS || pname == GL20.GL_LINK_STATUS || pname == GL20.GL_VALIDATE_STATUS) {
boolean result = gl.getProgramParameterb(programs.get(program), pname);
params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE);
} else {
params.put(gl.getProgramParameteri(programs.get(program), pname));
}
}
@Override
public String glGetProgramInfoLog (int program) {
return gl.getProgramInfoLog(programs.get(program));
}
@Override
public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetShaderiv (int shader, int pname, IntBuffer params) {
if (pname == GL20.GL_COMPILE_STATUS || pname == GL20.GL_DELETE_STATUS) {
boolean result = gl.getShaderParameterb(shaders.get(shader), pname);
params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE);
} else {
int result = gl.getShaderParameteri(shaders.get(shader), pname);
params.put(result);
}
}
@Override
public String glGetShaderInfoLog (int shader) {
return gl.getShaderInfoLog(shaders.get(shader));
}
@Override
public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) {
throw new GdxRuntimeException("glGetShaderPrecisionFormat not supported by GWT WebGL backend");
}
@Override
public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) {
throw new GdxRuntimeException("glGetShaderSource not supported by GWT WebGL backend");
}
@Override
public void glGetTexParameterfv (int target, int pname, FloatBuffer params) {
throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend");
}
@Override
public void glGetTexParameteriv (int target, int pname, IntBuffer params) {
throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend");
}
@Override
public void glGetUniformfv (int program, int location, FloatBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetUniformiv (int program, int location, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public int glGetUniformLocation (int program, String name) {
WebGLUniformLocation location = gl.getUniformLocation(programs.get(program), name);
return allocateUniformLocationId(program, location);
}
@Override
public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetVertexAttribiv (int index, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) {
throw new GdxRuntimeException("glGetVertexAttribPointer not supported by GWT WebGL backend");
}
@Override
public boolean glIsBuffer (int buffer) {
return gl.isBuffer(buffers.get(buffer));
}
@Override
public boolean glIsEnabled (int cap) {
return gl.isEnabled(cap);
}
@Override
public boolean glIsFramebuffer (int framebuffer) {
return gl.isFramebuffer(frameBuffers.get(framebuffer));
}
@Override
public boolean glIsProgram (int program) {
return gl.isProgram(programs.get(program));
}
@Override
public boolean glIsRenderbuffer (int renderbuffer) {
return gl.isRenderbuffer(renderBuffers.get(renderbuffer));
}
@Override
public boolean glIsShader (int shader) {
return gl.isShader(shaders.get(shader));
}
@Override
public boolean glIsTexture (int texture) {
return gl.isTexture(textures.get(texture));
}
@Override
public void glLinkProgram (int program) {
gl.linkProgram(programs.get(program));
}
@Override
public void glReleaseShaderCompiler () {
throw new GdxRuntimeException("not implemented");
}
@Override
public void glRenderbufferStorage (int target, int internalformat, int width, int height) {
gl.renderbufferStorage(target, internalformat, width, height);
}
@Override
public void glSampleCoverage (float value, boolean invert) {
gl.sampleCoverage(value, invert);
}
@Override
public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) {
throw new GdxRuntimeException("glShaderBinary not supported by GWT WebGL backend");
}
@Override
public void glShaderSource (int shader, String source) {
gl.shaderSource(shaders.get(shader), source);
}
@Override
public void glStencilFuncSeparate (int face, int func, int ref, int mask) {
gl.stencilFuncSeparate(face, func, ref, mask);
}
@Override
public void glStencilMaskSeparate (int face, int mask) {
gl.stencilMaskSeparate(face, mask);
}
@Override
public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) {
gl.stencilOpSeparate(face, fail, zfail, zpass);
}
@Override
public void glTexParameterfv (int target, int pname, FloatBuffer params) {
gl.texParameterf(target, pname, params.get());
}
@Override
public void glTexParameteri (int target, int pname, int param) {
gl.texParameterf(target, pname, param);
}
@Override
public void glTexParameteriv (int target, int pname, IntBuffer params) {
gl.texParameterf(target, pname, params.get());
}
@Override
public void glUniform1f (int location, float x) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform1f(loc, x);
}
@Override
public void glUniform1fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform1fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform1fv(loc, v.array());
}
}
@Override
public void glUniform1i (int location, int x) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform1i(loc, x);
}
@Override
public void glUniform1iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform1iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform1iv(loc, v.array());
}
}
@Override
public void glUniform2f (int location, float x, float y) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform2f(loc, x, y);
}
@Override
public void glUniform2fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform2fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
;
} else {
gl.uniform2fv(loc, v.array());
}
}
@Override
public void glUniform2i (int location, int x, int y) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform2i(loc, x, y);
}
@Override
public void glUniform2iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform2iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform2iv(loc, v.array());
}
}
@Override
public void glUniform3f (int location, float x, float y, float z) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform3f(loc, x, y, z);
}
@Override
public void glUniform3fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform3fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform3fv(loc, v.array());
}
}
@Override
public void glUniform3i (int location, int x, int y, int z) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform3i(loc, x, y, z);
}
@Override
public void glUniform3iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform3iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform3iv(loc, v.array());
}
}
@Override
public void glUniform4f (int location, float x, float y, float z, float w) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform4f(loc, x, y, z, w);
}
@Override
public void glUniform4fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform4fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform4fv(loc, v.array());
}
}
@Override
public void glUniform4i (int location, int x, int y, int z, int w) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform4i(loc, x, y, z, w);
}
@Override
public void glUniform4iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform4iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform4iv(loc, v.array());
}
}
@Override
public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix2fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix2fv(loc, transpose, value.array());
}
}
@Override
public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix3fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix3fv(loc, transpose, value.array());
}
}
@Override
public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix4fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix4fv(loc, transpose, value.array());
}
}
@Override
public void glUseProgram (int program) {
currProgram = program;
gl.useProgram(programs.get(program));
}
@Override
public void glValidateProgram (int program) {
gl.validateProgram(programs.get(program));
}
@Override
public void glVertexAttrib1f (int indx, float x) {
gl.vertexAttrib1f(indx, x);
}
@Override
public void glVertexAttrib1fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib1fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib1fv(indx, values.array());
}
}
@Override
public void glVertexAttrib2f (int indx, float x, float y) {
gl.vertexAttrib2f(indx, x, y);
}
@Override
public void glVertexAttrib2fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib2fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib2fv(indx, values.array());
}
}
@Override
public void glVertexAttrib3f (int indx, float x, float y, float z) {
gl.vertexAttrib3f(indx, x, y, z);
}
@Override
public void glVertexAttrib3fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib3fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib3fv(indx, values.array());
}
}
@Override
public void glVertexAttrib4f (int indx, float x, float y, float z, float w) {
gl.vertexAttrib4f(indx, x, y, z, w);
}
@Override
public void glVertexAttrib4fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib4fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib4fv(indx, values.array());
}
}
@Override
public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) {
throw new GdxRuntimeException("not implemented, vertex arrays aren't support in WebGL it seems");
}
@Override
public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) {
gl.vertexAttribPointer(indx, size, type, normalized, stride, ptr);
}
}
| false | true | public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) {
throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported.");
}
if (!(pixels instanceof ByteBuffer)) {
throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer.");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
| public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) {
throw new GdxRuntimeException("Only format RGBA and type UNSIGNED_BYTE are currently supported for glReadPixels(...).");
}
if (!(pixels instanceof ByteBuffer)) {
throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer for glReadPixels(...).");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
|
diff --git a/org.emftext.access/src/org/emftext/access/EMFTextAccessProxy.java b/org.emftext.access/src/org/emftext/access/EMFTextAccessProxy.java
index e3c9b8f2d..e6b63c1e6 100644
--- a/org.emftext.access/src/org/emftext/access/EMFTextAccessProxy.java
+++ b/org.emftext.access/src/org/emftext/access/EMFTextAccessProxy.java
@@ -1,259 +1,259 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* 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:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.access;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.emftext.access.resource.IColorManager;
import org.emftext.access.resource.IConfigurable;
import org.emftext.access.resource.IEditor;
import org.emftext.access.resource.ILocationMap;
import org.emftext.access.resource.IMetaInformation;
import org.emftext.access.resource.INewFileContentProvider;
import org.emftext.access.resource.IParseResult;
import org.emftext.access.resource.IParser;
import org.emftext.access.resource.IPrinter;
import org.emftext.access.resource.IResource;
import org.emftext.access.resource.IScanner;
import org.emftext.access.resource.IToken;
/**
* The EMFTextAccessProxy class can be used to access generated
* text resource plug-ins via a set of interfaces. This is
* particularly useful for tools that need to perform the same
* operations over a set of languages.
*
* The access to generated classes using interfaces that are not
* declared to be implemented by those classes is established by
* Java's reflection mechanisms. However, the EMFTextAccessProxy
* class allows to make transparent use of this mechanisms. The
* basic idea is to provide an object together with an interface
* the shall be used to access the methods in the object. The
* objects class must therefore contain the methods declared in
* the interface (i.e., the methods must have the same signature),
* but the class does not need to declare that it implements the
* interface.
*
* The central starting point to gather reflective access are the
* get() methods.
*
* Note that not all kinds of interfaces can be handled by the
* EMFTextAccessProxy! Methods that use generic types as return
* type or parameter can not be handled. This is due to Java's
* type erasure which removes type arguments during compilation.
* Thus, the type arguments of generic types are not known at
* run-time, which makes wrapping and unwrapping of objects
* impossible.
* Furthermore, the current implementation of the EMFTextAccessProxy
* can not handle multidimensional arrays.
*/
public class EMFTextAccessProxy implements InvocationHandler {
protected static Class<?> [] defaultAccessInterfaces = {
IColorManager.class,
IConfigurable.class,
IEditor.class,
ILocationMap.class,
IMetaInformation.class,
INewFileContentProvider.class,
IParser.class,
IParseResult.class,
IPrinter.class,
IResource.class,
IScanner.class,
IToken.class
};
protected Object impl;
protected Class<?> accessInterface;
private Class<?>[] accessInterfaces;
private EMFTextAccessProxy(Object impl, Class<?> accessInterface, Class<?>[] accessInterfaces) {
this.impl = impl;
this.accessInterface = accessInterface;
this.accessInterfaces = accessInterfaces;
}
/**
* Returns an instance of the given access interface that can be
* used to call the methods of 'impl'.
*
* @param impl
* @param accessInterface
*
* @return a dynamic proxy object implementing 'accessInterface' that
* delegates all method calls to 'impl'
*/
public static Object get(Object impl, Class<?> accessInterface) {
//proxies are not cached because also new objects (e.g., Parser, Printer) might be created
return get(impl, accessInterface, defaultAccessInterfaces);
}
/**
* Returns an instance of the given access interface that can be
* used to call the methods of 'impl'. In addition to the default
* set of interfaces that are declared to be used to access the
* object 'impl', more interfaces can be passed to this method.
*
* @param impl
* @param accessInterface
*
* @return a dynamic proxy object implementing 'accessInterface' that
* delegates all method calls to 'impl'
*/
public static Object get(Object impl, Class<?> accessInterface, Class<?>[] additionalAccessInterfaces) {
Class<?>[] allAccessInterfaces = new Class<?>[defaultAccessInterfaces.length + additionalAccessInterfaces.length];
int i = 0;
for (Class<?> nextInterface : defaultAccessInterfaces) {
allAccessInterfaces[i] = nextInterface;
i++;
}
for (Class<?> nextInterface : additionalAccessInterfaces) {
allAccessInterfaces[i] = nextInterface;
i++;
}
Object implObject = impl;
if (implObject instanceof Proxy) {
EMFTextAccessProxy accessProxy = (EMFTextAccessProxy) Proxy.getInvocationHandler(implObject);
implObject = accessProxy.impl;
}
//proxies are not cached because also new objects (e.g., Parser, Printer) might be created
return Proxy.newProxyInstance(
implObject.getClass().getClassLoader(),
new Class[] { accessInterface },
new EMFTextAccessProxy(implObject, accessInterface, allAccessInterfaces));
}
private boolean isAccessInterface(Class<?> type) {
for(int i = 0; i < accessInterfaces.length; i++) {
if (accessInterfaces[i] == type) {
return true;
}
}
return false;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
//currently access interface arguments are not support
Object result = null;
Object[] proxyArgs = null;
try {
Method implMethod;
implMethod = getMethod(method);
if (args != null) {
proxyArgs = new Object[args.length];
for (int a = 0; a < args.length; a++) {
Object arg = args[a];
proxyArgs[a] = unwrapIfNeeded(arg);
- proxyArgs[a] = unwrapArrayIfNeeded(implMethod, arg, implMethod.getParameterTypes()[a]);
+ proxyArgs[a] = unwrapArrayIfNeeded(implMethod, proxyArgs[a], implMethod.getParameterTypes()[a]);
}
}
result = implMethod.invoke(impl, proxyArgs);
Class<?> returnType = method.getReturnType();
// if the return type of a method is a access interface
// we need to wrap the returned object behind a proxy
result = wrapIfNeeded(returnType, result);
// if the return type of a method is an array containing
// elements of an access interface, we need to create
// a new array typed with the interface and create
// wrapper proxies for all elements contained in the
// returned result
result = wrapArrayIfNeeded(result, returnType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
EMFTextAccessPlugin.logError("Required method not defined: " + impl.getClass().getCanonicalName() + "." + method.getName(), null);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof IllegalArgumentException) {
throw (IllegalArgumentException) cause;
}
}
return result;
}
private Object unwrapArrayIfNeeded(Method implMethod, Object arg, Class<?> parameterType) {
Object unwrappedArray = arg;
// handle args that are arrays
if (arg != null && arg.getClass().isArray()) {
Class<?> componentType = parameterType.getComponentType();
unwrappedArray = Array.newInstance(componentType, Array.getLength(arg));
for (int i = 0; i < Array.getLength(arg); i++) {
Array.set(unwrappedArray, i, unwrapIfNeeded(Array.get(arg, i)));
}
}
return unwrappedArray;
}
private Object unwrapIfNeeded(Object arg) {
Object unwrappedArg = arg;
if (arg instanceof Proxy) {
Proxy argProxy = (Proxy) arg;
InvocationHandler handler = Proxy.getInvocationHandler(argProxy);
if (handler instanceof EMFTextAccessProxy) {
EMFTextAccessProxy emfHandler = (EMFTextAccessProxy) handler;
if (isAccessInterface(emfHandler.accessInterface)) {
unwrappedArg = emfHandler.impl;
}
}
}
return unwrappedArg;
}
private Object wrapArrayIfNeeded(Object result, Class<?> returnType) {
if (result != null && returnType.isArray()) {
Class<?> componentType = returnType.getComponentType();
if (isAccessInterface(componentType)) {
Object wrappingArray = Array.newInstance(componentType, Array.getLength(result));
for (int i = 0; i < Array.getLength(result); i++) {
Array.set(wrappingArray, i, wrapIfNeeded(componentType, Array.get(result, i)));
}
result = wrappingArray;
}
}
return result;
}
private Object wrapIfNeeded(Class<?> type, Object result) {
if (result != null && isAccessInterface(type)) {
result = EMFTextAccessProxy.get(result, type, accessInterfaces);
}
return result;
}
private Method getMethod(Method method) throws NoSuchMethodException {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
// first look for the exact method
try {
return impl.getClass().getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
// ignore exception and continue to search
}
Method[] methods = impl.getClass().getMethods();
// then look for a method with the same name (do not care about parameter types)
// this is needed to find methods that use types from the generated plug-ins as
// parameters
for (Method nextMethod : methods) {
if (methodName.equals(nextMethod.getName())) {
return nextMethod;
}
}
throw new NoSuchMethodException();
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
//currently access interface arguments are not support
Object result = null;
Object[] proxyArgs = null;
try {
Method implMethod;
implMethod = getMethod(method);
if (args != null) {
proxyArgs = new Object[args.length];
for (int a = 0; a < args.length; a++) {
Object arg = args[a];
proxyArgs[a] = unwrapIfNeeded(arg);
proxyArgs[a] = unwrapArrayIfNeeded(implMethod, arg, implMethod.getParameterTypes()[a]);
}
}
result = implMethod.invoke(impl, proxyArgs);
Class<?> returnType = method.getReturnType();
// if the return type of a method is a access interface
// we need to wrap the returned object behind a proxy
result = wrapIfNeeded(returnType, result);
// if the return type of a method is an array containing
// elements of an access interface, we need to create
// a new array typed with the interface and create
// wrapper proxies for all elements contained in the
// returned result
result = wrapArrayIfNeeded(result, returnType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
EMFTextAccessPlugin.logError("Required method not defined: " + impl.getClass().getCanonicalName() + "." + method.getName(), null);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof IllegalArgumentException) {
throw (IllegalArgumentException) cause;
}
}
return result;
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
//currently access interface arguments are not support
Object result = null;
Object[] proxyArgs = null;
try {
Method implMethod;
implMethod = getMethod(method);
if (args != null) {
proxyArgs = new Object[args.length];
for (int a = 0; a < args.length; a++) {
Object arg = args[a];
proxyArgs[a] = unwrapIfNeeded(arg);
proxyArgs[a] = unwrapArrayIfNeeded(implMethod, proxyArgs[a], implMethod.getParameterTypes()[a]);
}
}
result = implMethod.invoke(impl, proxyArgs);
Class<?> returnType = method.getReturnType();
// if the return type of a method is a access interface
// we need to wrap the returned object behind a proxy
result = wrapIfNeeded(returnType, result);
// if the return type of a method is an array containing
// elements of an access interface, we need to create
// a new array typed with the interface and create
// wrapper proxies for all elements contained in the
// returned result
result = wrapArrayIfNeeded(result, returnType);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
EMFTextAccessPlugin.logError("Required method not defined: " + impl.getClass().getCanonicalName() + "." + method.getName(), null);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof IllegalArgumentException) {
throw (IllegalArgumentException) cause;
}
}
return result;
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java
index a83afdfe2..114b395cb 100755
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AsynchronousProcessor.java
@@ -1,645 +1,645 @@
/*
* Copyright 2013 Jeanfrancois 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.
*/
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.cpr;
import org.atmosphere.util.EndpointMapper;
import org.atmosphere.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.atmosphere.cpr.Action.TYPE.SKIP_ATMOSPHEREHANDLER;
import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;
import static org.atmosphere.cpr.AtmosphereFramework.AtmosphereHandlerWrapper;
import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR;
import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRANSPORT;
/**
* Base class which implement the semantics of suspending and resuming of a
* Comet/WebSocket Request.
*
* @author Jeanfrancois Arcand
*/
public abstract class AsynchronousProcessor implements AsyncSupport<AtmosphereResourceImpl> {
private static final Logger logger = LoggerFactory.getLogger(AsynchronousProcessor.class);
protected static final Action timedoutAction = new Action(Action.TYPE.TIMEOUT);
protected static final Action cancelledAction = new Action(Action.TYPE.CANCELLED);
protected final AtmosphereConfig config;
protected final ConcurrentHashMap<AtmosphereRequest, AtmosphereResource>
aliveRequests = new ConcurrentHashMap<AtmosphereRequest, AtmosphereResource>();
private boolean trackActiveRequest = false;
private final ScheduledExecutorService closedDetector = Executors.newScheduledThreadPool(1);
private final EndpointMapper<AtmosphereHandlerWrapper> mapper;
public AsynchronousProcessor(AtmosphereConfig config) {
this.config = config;
mapper = config.framework().endPointMapper();
}
@Override
public void init(ServletConfig sc) throws ServletException {
String maxInactive = sc.getInitParameter(MAX_INACTIVE) != null ? sc.getInitParameter(MAX_INACTIVE) :
config.getInitParameter(MAX_INACTIVE);
if (maxInactive != null) {
trackActiveRequest = true;
final long maxInactiveTime = Long.parseLong(maxInactive);
if (maxInactiveTime <= 0) return;
closedDetector.scheduleAtFixedRate(new Runnable() {
public void run() {
for (AtmosphereRequest req : aliveRequests.keySet()) {
long l = (Long) req.getAttribute(MAX_INACTIVE);
if (l > 0 && System.currentTimeMillis() - l > maxInactiveTime) {
try {
logger.trace("Close detector disconnecting {}. Current size {}", req.resource(), aliveRequests.size());
AtmosphereResourceImpl r = (AtmosphereResourceImpl) aliveRequests.remove(req);
cancelled(req, r.getResponse(false));
} catch (Throwable e) {
logger.warn("closedDetector", e);
} finally {
try {
req.setAttribute(MAX_INACTIVE, (long) -1);
} catch (Throwable t) {
logger.trace("closedDetector", t);
}
}
}
}
}
}, 0, 1, TimeUnit.SECONDS);
}
}
/**
* Is {@link HttpSession} supported
*
* @return true if supported
*/
protected boolean supportSession() {
return config.isSupportSession();
}
/**
* Return the container's name.
*/
public String getContainerName() {
return config.getServletConfig().getServletContext().getServerInfo();
}
/**
* All proprietary Comet based {@link Servlet} must invoke the suspended
* method when the first request comes in. The returned value, of type
* {@link Action}, tells the proprietary Comet {@link Servlet}
* to suspended or not the current {@link AtmosphereResponse}.
*
* @param request the {@link AtmosphereRequest}
* @param response the {@link AtmosphereResponse}
* @return action the Action operation.
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
public Action suspended(AtmosphereRequest request, AtmosphereResponse response) throws IOException, ServletException {
return action(request, response);
}
/**
* Invoke the {@link AtmosphereHandler#onRequest} method.
*
* @param req the {@link AtmosphereRequest}
* @param res the {@link AtmosphereResponse}
* @return action the Action operation.
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
Action action(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
if (Utils.webSocketEnabled(req) && !supportWebSocket()) {
res.setStatus(501);
res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported");
res.flushBuffer();
return new Action();
}
if (config.handlers().isEmpty()) {
- logger.error("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @AtmosphereHandlerService");
- throw new AtmosphereMappingException("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @AtmosphereHandlerService");
+ logger.error("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
+ throw new AtmosphereMappingException("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
}
if (res.request() == null) {
res.request(req);
}
if (supportSession()) {
// Create the session needed to support the Resume
// operation from disparate requests.
req.getSession(true);
}
req.setAttribute(FrameworkConfig.SUPPORT_SESSION, supportSession());
AtmosphereHandlerWrapper handlerWrapper = map(req);
if (config.getBroadcasterFactory() == null) {
logger.error("Atmosphere is misconfigured and will not work. BroadcasterFactory is null");
return Action.CANCELLED;
}
AtmosphereResourceImpl resource = configureWorkflow(null, handlerWrapper, req, res);
// Globally defined
Action a = invokeInterceptors(config.framework().interceptors(), resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Per AtmosphereHandler
a = invokeInterceptors(handlerWrapper.interceptors, resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Remap occured.
if (req.getAttribute(FrameworkConfig.NEW_MAPPING) != null) {
req.removeAttribute(FrameworkConfig.NEW_MAPPING);
handlerWrapper = config.handlers().get(path(req));
if (handlerWrapper == null) {
logger.debug("Remap {}", resource.uuid());
throw new AtmosphereMappingException("Invalid state. No AtmosphereHandler maps request for " + req.getRequestURI());
}
resource = configureWorkflow(resource, handlerWrapper, req, res);
resource.setBroadcaster(handlerWrapper.broadcaster);
}
//Unit test mock the request and will throw NPE.
boolean skipAtmosphereHandler = req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) != null
? (Boolean) req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) : Boolean.FALSE;
if (!skipAtmosphereHandler) {
try {
handlerWrapper.atmosphereHandler.onRequest(resource);
} catch (IOException t) {
resource.onThrowable(t);
throw t;
}
}
postInterceptors(handlerWrapper.interceptors, resource);
postInterceptors(config.framework().interceptors(), resource);
if (trackActiveRequest && resource.isSuspended() && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) {
req.setAttribute(MAX_INACTIVE, System.currentTimeMillis());
aliveRequests.put(req, resource);
}
Action action = skipAtmosphereHandler ? Action.CANCELLED : resource.action();
if (supportSession() && action.type().equals(Action.TYPE.SUSPEND)) {
// Do not allow times out.
SessionTimeoutSupport.setupTimeout(req.getSession());
}
logger.trace("Action for {} was {} with transport " + req.getHeader(X_ATMOSPHERE_TRANSPORT), req.resource() != null ? req.resource().uuid() : "null", action);
return action;
}
private AtmosphereResourceImpl configureWorkflow(AtmosphereResourceImpl resource,
AtmosphereHandlerWrapper handlerWrapper,
AtmosphereRequest req, AtmosphereResponse res) {
config.getBroadcasterFactory().add(handlerWrapper.broadcaster, handlerWrapper.broadcaster.getID());
// Check Broadcaster state. If destroyed, replace it.
Broadcaster b = handlerWrapper.broadcaster;
if (b.isDestroyed()) {
BroadcasterFactory f = config.getBroadcasterFactory();
synchronized (f) {
f.remove(b, b.getID());
try {
handlerWrapper.broadcaster = f.get(b.getID());
} catch (IllegalStateException ex) {
// Something wrong occurred, let's not fail and loookup the value
logger.trace("", ex);
// fallback to lookup
handlerWrapper.broadcaster = f.lookup(b.getID(), true);
}
}
}
if (resource == null) {
resource = (AtmosphereResourceImpl) req.getAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE);
}
if (resource == null) {
// TODO: cast is dangerous
resource = (AtmosphereResourceImpl)
AtmosphereResourceFactory.getDefault().create(config, handlerWrapper.broadcaster, res, this, handlerWrapper.atmosphereHandler);
} else {
// TODO: REDESIGN, UGLY.
try {
// Make sure it wasn't set before
resource.getBroadcaster();
} catch (IllegalStateException ex) {
resource.setBroadcaster(handlerWrapper.broadcaster);
}
resource.atmosphereHandler(handlerWrapper.atmosphereHandler);
}
req.setAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE, resource);
req.setAttribute(FrameworkConfig.ATMOSPHERE_HANDLER_WRAPPER, handlerWrapper);
req.setAttribute(SKIP_ATMOSPHEREHANDLER.name(), Boolean.FALSE);
return resource;
}
private String path(AtmosphereRequest request) {
String path;
String pathInfo = null;
try {
pathInfo = request.getPathInfo();
} catch (IllegalStateException ex) {
// http://java.net/jira/browse/GRIZZLY-1301
}
if (pathInfo != null) {
path = request.getServletPath() + pathInfo;
} else {
path = request.getServletPath();
}
if (path == null || path.isEmpty()) {
path = "/";
}
return path;
}
private Action invokeInterceptors(List<AtmosphereInterceptor> c, AtmosphereResource r) {
Action a = Action.CONTINUE;
for (AtmosphereInterceptor arc : c) {
a = arc.inspect(r);
if (a == null) {
logger.debug("Action was null for {}", arc);
a = Action.CANCELLED;
}
boolean skip = a.type() == SKIP_ATMOSPHEREHANDLER;
if (skip) {
logger.debug("AtmosphereInterceptor {} asked to skip the AtmosphereHandler for {}", arc, r.uuid());
r.getRequest().setAttribute(SKIP_ATMOSPHEREHANDLER.name(), Boolean.TRUE);
}
if (a.type() != Action.TYPE.CONTINUE) {
logger.trace("Interceptor {} interrupted the dispatch for {} with " + a, arc, r.uuid());
return a;
}
}
return a;
}
private void postInterceptors(List<AtmosphereInterceptor> c, AtmosphereResource r) {
for (int i = c.size() - 1; i > -1; i--) {
c.get(i).postInspect(r);
}
}
/**
* {@inheritDoc}
*/
public void action(AtmosphereResourceImpl r) {
if (trackActiveRequest) {
aliveRequests.remove(r.getRequest(false));
}
}
/**
* Return the {@link AtmosphereHandler} mapped to the passed servlet-path.
*
* @param req the {@link AtmosphereResponse}
* @return the {@link AtmosphereHandler} mapped to the passed servlet-path.
* @throws javax.servlet.ServletException
*/
protected AtmosphereHandlerWrapper map(AtmosphereRequest req) throws ServletException {
AtmosphereHandlerWrapper atmosphereHandlerWrapper = mapper.map(req, config.handlers());
if (atmosphereHandlerWrapper == null) {
logger.debug("No AtmosphereHandler maps request for {} with mapping {}", req.getRequestURI(), config.handlers());
throw new AtmosphereMappingException("No AtmosphereHandler maps request for " + req.getRequestURI());
}
config.getBroadcasterFactory().add(atmosphereHandlerWrapper.broadcaster,
atmosphereHandlerWrapper.broadcaster.getID());
return atmosphereHandlerWrapper;
}
/**
* All proprietary Comet based {@link Servlet} must invoke the resume
* method when the Atmosphere's application decide to resume the {@link AtmosphereResponse}.
* The returned value, of type
* {@link Action}, tells the proprietary Comet {@link Servlet}
* to resume (again), suspended or do nothing with the current {@link AtmosphereResponse}.
*
* @param request the {@link AtmosphereRequest}
* @param response the {@link AtmosphereResponse}
* @return action the Action operation.
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
public Action resumed(AtmosphereRequest request, AtmosphereResponse response)
throws IOException, ServletException {
AtmosphereResourceImpl r =
(AtmosphereResourceImpl) request.getAttribute(FrameworkConfig.ATMOSPHERE_RESOURCE);
if (r == null) return Action.CANCELLED; // We are cancelled already
AtmosphereHandler atmosphereHandler = r.getAtmosphereHandler();
AtmosphereResourceEvent event = r.getAtmosphereResourceEvent();
if (event != null && event.isResuming() && !event.isCancelled()) {
synchronized (r) {
atmosphereHandler.onStateChange(event);
}
}
return Action.RESUME;
}
/**
* All proprietary Comet based {@link Servlet} must invoke the timedout
* method when the underlying WebServer time out the {@link AtmosphereResponse}.
* The returned value, of type
* {@link Action}, tells the proprietary Comet {@link Servlet}
* to resume (again), suspended or do nothing with the current {@link AtmosphereResponse}.
*
* @param req the {@link AtmosphereRequest}
* @param res the {@link AtmosphereResponse}
* @return action the Action operation.
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
public Action timedout(AtmosphereRequest req, AtmosphereResponse res)
throws IOException, ServletException {
logger.trace("Timing out {}", req);
if (trackActiveRequest(req) && completeLifecycle(req.resource(), false)) {
config.framework().notify(Action.TYPE.TIMEOUT, req, res);
}
return timedoutAction;
}
protected boolean trackActiveRequest(AtmosphereRequest req) {
if (trackActiveRequest) {
try {
long l = (Long) req.getAttribute(MAX_INACTIVE);
if (l == -1) {
// The closedDetector closed the connection.
return false;
}
req.setAttribute(MAX_INACTIVE, (long) -1);
// GlassFish
} catch (Throwable ex) {
logger.trace("Request already recycled", req);
// Request is no longer active, return
return false;
}
}
return true;
}
/**
* Cancel or times out an {@link AtmosphereResource} by invoking it's associated {@link AtmosphereHandler#onStateChange(AtmosphereResourceEvent)}
*
* @param r an {@link AtmosphereResource}
* @param cancelled true if cancelled, false if timedout
* @return true if the operation was executed.
*/
public boolean completeLifecycle(final AtmosphereResource r, boolean cancelled) {
if (r != null && !r.isCancelled()) {
logger.trace("Finishing lifecycle for AtmosphereResource {}", r.uuid());
final AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(r);
synchronized (impl) {
try {
if (impl.isCancelled()) {
logger.trace("{} is already cancelled", impl.uuid());
return false;
}
AtmosphereResourceEventImpl e = impl.getAtmosphereResourceEvent();
if (!e.isClosedByClient()) {
if (cancelled) {
e.setCancelled(true);
} else {
e.setIsResumedOnTimeout(true);
Broadcaster b = r.getBroadcaster();
if (b instanceof DefaultBroadcaster) {
((DefaultBroadcaster) b).broadcastOnResume(r);
}
// TODO: Was it there for legacy reason?
// impl.getAtmosphereResourceEvent().setIsResumedOnTimeout(impl.resumeOnBroadcast());
}
}
invokeAtmosphereHandler(impl);
try {
impl.getResponse().getOutputStream().close();
} catch (Throwable t) {
try {
impl.getResponse().getWriter().close();
} catch (Throwable t2) {
}
}
} catch (Throwable ex) {
// Something wrong happened, ignore the exception
logger.trace("Failed to cancel resource: {}", impl.uuid(), ex);
} finally {
try {
impl.notifyListeners();
impl.setIsInScope(false);
impl.cancel();
} catch (Throwable t) {
logger.trace("completeLifecycle", t);
} finally {
impl._destroy();
}
}
}
return true;
} else {
logger.debug("AtmosphereResource was null, failed to cancel AtmosphereRequest {}");
return false;
}
}
/**
* Invoke the associated {@link AtmosphereHandler}. This method must be synchronized on an AtmosphereResource
*
* @param r a {@link AtmosphereResourceImpl}
* @throws IOException
*/
protected void invokeAtmosphereHandler(AtmosphereResourceImpl r) throws IOException {
if (!r.isInScope()) {
logger.trace("AtmosphereResource out of scope {}", r.uuid());
return;
}
AtmosphereRequest req = r.getRequest(false);
String disableOnEvent = r.getAtmosphereConfig().getInitParameter(ApplicationConfig.DISABLE_ONSTATE_EVENT);
r.getAtmosphereResourceEvent().setMessage(r.writeOnTimeout());
try {
if (disableOnEvent == null || !disableOnEvent.equals(String.valueOf(true))) {
AtmosphereHandler atmosphereHandler = r.getAtmosphereHandler();
if (atmosphereHandler != null) {
try {
atmosphereHandler.onStateChange(r.getAtmosphereResourceEvent());
} finally {
Meteor m = (Meteor) req.getAttribute(AtmosphereResourceImpl.METEOR);
if (m != null) {
m.destroy();
}
}
}
}
} catch (IOException ex) {
try {
r.onThrowable(ex);
} catch (Throwable t) {
logger.warn("failed calling onThrowable()", ex);
}
}
}
/**
* All proprietary Comet based {@link Servlet} must invoke the cancelled
* method when the underlying WebServer detect that the client closed
* the connection.
*
* @param req the {@link AtmosphereRequest}
* @param res the {@link AtmosphereResponse}
* @return action the Action operation.
* @throws java.io.IOException
* @throws javax.servlet.ServletException
*/
public Action cancelled(AtmosphereRequest req, AtmosphereResponse res)
throws IOException, ServletException {
logger.trace("Cancelling {}", req);
if (trackActiveRequest(req) && completeLifecycle(req.resource(), true)) {
config.framework().notify(Action.TYPE.CANCELLED, req, res);
}
return cancelledAction;
}
protected void shutdown() {
closedDetector.shutdownNow();
for (AtmosphereResource resource : aliveRequests.values()) {
try {
resource.resume();
} catch (Throwable t) {
// Something wrong happenned, ignore the exception
logger.debug("failed on resume: " + resource, t);
}
}
}
@Override
public boolean supportWebSocket() {
return false;
}
/**
* An Callback class that can be used by Framework integrator to handle the close/timedout/resume life cycle
* of an {@link AtmosphereResource}. This class support only support {@link AsyncSupport} implementation that
* extends {@link AsynchronousProcessor}
*/
public final static class AsynchronousProcessorHook {
private final AtmosphereResourceImpl r;
public AsynchronousProcessorHook(AtmosphereResourceImpl r) {
this.r = r;
if (!AsynchronousProcessor.class.isAssignableFrom(r.asyncSupport.getClass())) {
throw new IllegalStateException("AsyncSupport must extends AsynchronousProcessor");
}
}
public void closed() {
try {
((AsynchronousProcessor) r.asyncSupport).cancelled(r.getRequest(false), r.getResponse(false));
} catch (IOException e) {
logger.debug("", e);
} catch (ServletException e) {
logger.debug("", e);
}
}
public void timedOut() {
try {
((AsynchronousProcessor) r.asyncSupport).timedout(r.getRequest(false), r.getResponse(false));
} catch (IOException e) {
logger.debug("", e);
} catch (ServletException e) {
logger.debug("", e);
}
}
public void resume() {
((AsynchronousProcessor) r.asyncSupport).action(r);
}
}
}
| true | true | Action action(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
if (Utils.webSocketEnabled(req) && !supportWebSocket()) {
res.setStatus(501);
res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported");
res.flushBuffer();
return new Action();
}
if (config.handlers().isEmpty()) {
logger.error("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @AtmosphereHandlerService");
throw new AtmosphereMappingException("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @AtmosphereHandlerService");
}
if (res.request() == null) {
res.request(req);
}
if (supportSession()) {
// Create the session needed to support the Resume
// operation from disparate requests.
req.getSession(true);
}
req.setAttribute(FrameworkConfig.SUPPORT_SESSION, supportSession());
AtmosphereHandlerWrapper handlerWrapper = map(req);
if (config.getBroadcasterFactory() == null) {
logger.error("Atmosphere is misconfigured and will not work. BroadcasterFactory is null");
return Action.CANCELLED;
}
AtmosphereResourceImpl resource = configureWorkflow(null, handlerWrapper, req, res);
// Globally defined
Action a = invokeInterceptors(config.framework().interceptors(), resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Per AtmosphereHandler
a = invokeInterceptors(handlerWrapper.interceptors, resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Remap occured.
if (req.getAttribute(FrameworkConfig.NEW_MAPPING) != null) {
req.removeAttribute(FrameworkConfig.NEW_MAPPING);
handlerWrapper = config.handlers().get(path(req));
if (handlerWrapper == null) {
logger.debug("Remap {}", resource.uuid());
throw new AtmosphereMappingException("Invalid state. No AtmosphereHandler maps request for " + req.getRequestURI());
}
resource = configureWorkflow(resource, handlerWrapper, req, res);
resource.setBroadcaster(handlerWrapper.broadcaster);
}
//Unit test mock the request and will throw NPE.
boolean skipAtmosphereHandler = req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) != null
? (Boolean) req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) : Boolean.FALSE;
if (!skipAtmosphereHandler) {
try {
handlerWrapper.atmosphereHandler.onRequest(resource);
} catch (IOException t) {
resource.onThrowable(t);
throw t;
}
}
postInterceptors(handlerWrapper.interceptors, resource);
postInterceptors(config.framework().interceptors(), resource);
if (trackActiveRequest && resource.isSuspended() && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) {
req.setAttribute(MAX_INACTIVE, System.currentTimeMillis());
aliveRequests.put(req, resource);
}
Action action = skipAtmosphereHandler ? Action.CANCELLED : resource.action();
if (supportSession() && action.type().equals(Action.TYPE.SUSPEND)) {
// Do not allow times out.
SessionTimeoutSupport.setupTimeout(req.getSession());
}
logger.trace("Action for {} was {} with transport " + req.getHeader(X_ATMOSPHERE_TRANSPORT), req.resource() != null ? req.resource().uuid() : "null", action);
return action;
}
| Action action(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
if (Utils.webSocketEnabled(req) && !supportWebSocket()) {
res.setStatus(501);
res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported");
res.flushBuffer();
return new Action();
}
if (config.handlers().isEmpty()) {
logger.error("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
throw new AtmosphereMappingException("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
}
if (res.request() == null) {
res.request(req);
}
if (supportSession()) {
// Create the session needed to support the Resume
// operation from disparate requests.
req.getSession(true);
}
req.setAttribute(FrameworkConfig.SUPPORT_SESSION, supportSession());
AtmosphereHandlerWrapper handlerWrapper = map(req);
if (config.getBroadcasterFactory() == null) {
logger.error("Atmosphere is misconfigured and will not work. BroadcasterFactory is null");
return Action.CANCELLED;
}
AtmosphereResourceImpl resource = configureWorkflow(null, handlerWrapper, req, res);
// Globally defined
Action a = invokeInterceptors(config.framework().interceptors(), resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Per AtmosphereHandler
a = invokeInterceptors(handlerWrapper.interceptors, resource);
if (a.type() != Action.TYPE.CONTINUE) {
return a;
}
// Remap occured.
if (req.getAttribute(FrameworkConfig.NEW_MAPPING) != null) {
req.removeAttribute(FrameworkConfig.NEW_MAPPING);
handlerWrapper = config.handlers().get(path(req));
if (handlerWrapper == null) {
logger.debug("Remap {}", resource.uuid());
throw new AtmosphereMappingException("Invalid state. No AtmosphereHandler maps request for " + req.getRequestURI());
}
resource = configureWorkflow(resource, handlerWrapper, req, res);
resource.setBroadcaster(handlerWrapper.broadcaster);
}
//Unit test mock the request and will throw NPE.
boolean skipAtmosphereHandler = req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) != null
? (Boolean) req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) : Boolean.FALSE;
if (!skipAtmosphereHandler) {
try {
handlerWrapper.atmosphereHandler.onRequest(resource);
} catch (IOException t) {
resource.onThrowable(t);
throw t;
}
}
postInterceptors(handlerWrapper.interceptors, resource);
postInterceptors(config.framework().interceptors(), resource);
if (trackActiveRequest && resource.isSuspended() && req.getAttribute(FrameworkConfig.CANCEL_SUSPEND_OPERATION) == null) {
req.setAttribute(MAX_INACTIVE, System.currentTimeMillis());
aliveRequests.put(req, resource);
}
Action action = skipAtmosphereHandler ? Action.CANCELLED : resource.action();
if (supportSession() && action.type().equals(Action.TYPE.SUSPEND)) {
// Do not allow times out.
SessionTimeoutSupport.setupTimeout(req.getSession());
}
logger.trace("Action for {} was {} with transport " + req.getHeader(X_ATMOSPHERE_TRANSPORT), req.resource() != null ? req.resource().uuid() : "null", action);
return action;
}
|
diff --git a/src/main/java/org/thymeleaf/standard/expression/LinkExpression.java b/src/main/java/org/thymeleaf/standard/expression/LinkExpression.java
index cd5d88e9..b959ec1d 100755
--- a/src/main/java/org/thymeleaf/standard/expression/LinkExpression.java
+++ b/src/main/java/org/thymeleaf/standard/expression/LinkExpression.java
@@ -1,508 +1,509 @@
/*
* =============================================================================
*
* Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.standard.expression;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.Configuration;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IContext;
import org.thymeleaf.context.IProcessingContext;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.exceptions.TemplateProcessingException;
import org.thymeleaf.util.StringUtils;
import org.thymeleaf.util.Validate;
/**
*
* @author Daniel Fernández
* @author Josh Long
* @since 1.1
*
*/
public final class LinkExpression extends SimpleExpression {
private static final Logger logger = LoggerFactory.getLogger(LinkExpression.class);
private static final long serialVersionUID = -564516592085017252L;
static final char SELECTOR = '@';
private static final char PARAMS_START_CHAR = '(';
private static final char PARAMS_END_CHAR = ')';
private static final Pattern LINK_PATTERN =
Pattern.compile("^\\s*\\@\\{(.+?)\\}\\s*$", Pattern.DOTALL);
private static final String URL_PARAM_NO_VALUE = "%%%__NO_VALUE__%%%";
private final Expression base;
private final AssignationSequence parameters;
public LinkExpression(final Expression base, final AssignationSequence parameters) {
super();
Validate.notNull(base, "Base cannot be null");
this.base = base;
this.parameters = parameters;
}
public Expression getBase() {
return this.base;
}
public AssignationSequence getParameters() {
return this.parameters;
}
public boolean hasParameters() {
return this.parameters != null && this.parameters.size() > 0;
}
@Override
public String getStringRepresentation() {
final StringBuilder sb = new StringBuilder();
sb.append(SELECTOR);
sb.append(SimpleExpression.EXPRESSION_START_CHAR);
sb.append(this.base);
if (hasParameters()) {
sb.append(PARAMS_START_CHAR);
sb.append(this.parameters.getStringRepresentation());
sb.append(PARAMS_END_CHAR);
}
sb.append(SimpleExpression.EXPRESSION_END_CHAR);
return sb.toString();
}
static LinkExpression parseLink(final String input) {
final Matcher matcher = LINK_PATTERN.matcher(input);
if (!matcher.matches()) {
return null;
}
final String content = matcher.group(1);
if (StringUtils.isEmptyOrWhitespace(content)) {
return null;
}
final String trimmedInput = content.trim();
if (trimmedInput.endsWith(String.valueOf(PARAMS_END_CHAR))) {
boolean inLiteral = false;
int nestParLevel = 0;
for (int i = trimmedInput.length() - 1; i >= 0; i--) {
final char c = trimmedInput.charAt(i);
if (c == TextLiteralExpression.DELIMITER) {
if (i == 0 || content.charAt(i - 1) != '\\') {
inLiteral = !inLiteral;
}
} else if (c == PARAMS_END_CHAR) {
nestParLevel++;
} else if (c == PARAMS_START_CHAR) {
nestParLevel--;
if (nestParLevel < 0) {
return null;
}
if (nestParLevel == 0) {
if (i == 0) {
// It was not a parameter specification, but a base URL surrounded by parentheses!
final Expression baseExpr = parseBaseDefaultAsLiteral(trimmedInput);
if (baseExpr == null) {
return null;
}
return new LinkExpression(baseExpr, null);
}
final String base = trimmedInput.substring(0, i).trim();
final String parameters = trimmedInput.substring(i + 1, trimmedInput.length() - 1).trim();
final Expression baseExpr = parseBaseDefaultAsLiteral(base);
if (baseExpr == null) {
return null;
}
final AssignationSequence parametersAssigSeq =
AssignationSequence.parse(
parameters, true /* allow parameters without value or equals sign */);
if (parametersAssigSeq == null) {
return null;
}
return new LinkExpression(baseExpr, parametersAssigSeq);
}
}
}
return null;
}
final Expression baseExpr = parseBaseDefaultAsLiteral(trimmedInput);
if (baseExpr == null) {
return null;
}
return new LinkExpression(baseExpr, null);
}
private static Expression parseBaseDefaultAsLiteral(final String base) {
if (StringUtils.isEmptyOrWhitespace(base)) {
return null;
}
final Expression expr = Expression.parse(base);
if (expr == null) {
return Expression.parse(TextLiteralExpression.wrapStringIntoLiteral(base));
}
return expr;
}
static Object executeLink(final Configuration configuration,
final IProcessingContext processingContext, final LinkExpression expression,
final IStandardVariableExpressionEvaluator expressionEvaluator,
final StandardExpressionExecutionContext expContext) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Evaluating link: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation());
}
final Expression baseExpression = expression.getBase();
Object base =
Expression.execute(configuration, processingContext, baseExpression, expressionEvaluator, expContext);
base = LiteralValue.unwrap(base);
- if (base == null || !(base instanceof String) || StringUtils.isEmptyOrWhitespace((String) base)) {
- throw new TemplateProcessingException(
- "Base for link URL creation must be a non-null and non-empty String " +
- "(currently: " + (base == null? null : base.getClass().getName()) + ")");
+ if (base != null && !(base instanceof String)) {
+ base = base.toString();
+ }
+ if (base == null || StringUtils.isEmptyOrWhitespace((String) base)) {
+ base = "";
}
String linkBase = (String) base;
if (!isWebContext(processingContext.getContext()) && !isLinkBaseAbsolute(linkBase) && !isLinkBaseServerRelative(linkBase)) {
throw new TemplateProcessingException(
"Link base \"" + linkBase + "\" cannot be context relative (/) or page relative unless you implement the " +
IWebContext.class.getName() + " interface (context is of class: " +
processingContext.getContext().getClass().getName() + ")");
}
@SuppressWarnings("unchecked")
final Map<String,List<Object>> parameters =
(expression.hasParameters()?
resolveParameters(configuration, processingContext, expression, expressionEvaluator, expContext) :
(Map<String,List<Object>>) Collections.EMPTY_MAP);
/*
* Detect URL fragments (selectors after '#') so that they can be output at the end of
* the URL, after parameters.
*/
final int hashPosition = linkBase.indexOf('#');
String urlFragment = "";
// If hash position == 0 we will not consider it as marking an
// URL fragment.
if (hashPosition > 0) {
// URL fragment String will include the # sign
urlFragment = linkBase.substring(hashPosition);
linkBase = linkBase.substring(0, hashPosition);
}
/*
* Check for the existence of a question mark symbol in the link base itself
*/
final int questionMarkPosition = linkBase.indexOf('?');
final StringBuilder parametersBuilder = new StringBuilder();
for (final Map.Entry<String,List<Object>> parameterEntry : parameters.entrySet()) {
final String parameterName = parameterEntry.getKey();
final List<Object> parameterValues = parameterEntry.getValue();
for (final Object parameterObjectValue : parameterValues) {
// Insert a separator with the previous parameter, if needed
if (parametersBuilder.length() == 0) {
if (questionMarkPosition == -1) {
parametersBuilder.append("?");
} else {
parametersBuilder.append("&");
}
} else {
parametersBuilder.append("&");
}
final String parameterValue =
(parameterObjectValue == null? "" : parameterObjectValue.toString());
if (URL_PARAM_NO_VALUE.equals(parameterValue)) {
// This is a parameter without a value and even without an "=" symbol
parametersBuilder.append(parameterName);
} else {
try {
parametersBuilder.append(parameterName).append("=").append(URLEncoder.encode(parameterValue, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new TemplateProcessingException("Exception while processing link parameters", e);
}
}
}
}
/*
* Context is not web: URLs can only be absolute or server-relative
*/
if (!isWebContext(processingContext.getContext())) {
if (isLinkBaseAbsolute(linkBase)) {
return linkBase + parametersBuilder + urlFragment;
}
// isLinkBaseServerRelative(linkBase) == true
return linkBase.substring(1) + parametersBuilder + urlFragment;
}
/*
* Context is web
*/
final IWebContext webContext = (IWebContext) processingContext.getContext();
final HttpServletRequest request = webContext.getHttpServletRequest();
final HttpServletResponse response = webContext.getHttpServletResponse();
String url = null;
if (isLinkBaseContextRelative(linkBase)) {
url = request.getContextPath() + linkBase + parametersBuilder + urlFragment;
} else if (isLinkBaseServerRelative(linkBase)) {
// remove the "~" from the link base
url = linkBase.substring(1) + parametersBuilder + urlFragment;
} else if (isLinkBaseAbsolute(linkBase)) {
url = linkBase + parametersBuilder + urlFragment;
} else {
// Link base is current-URL-relative
url = linkBase + parametersBuilder + urlFragment;
}
return (response != null? response.encodeURL(url) : url);
}
private static boolean isWebContext(final IContext context) {
return context instanceof IWebContext;
}
private static boolean isLinkBaseAbsolute(final String linkBase) {
return (linkBase.contains("://") ||
linkBase.toLowerCase().startsWith("mailto:") || // Email URLs
linkBase.startsWith("//")); // protocol-relative URLs
}
private static boolean isLinkBaseContextRelative(final String linkBase) {
return linkBase.startsWith("/") && !linkBase.startsWith("//");
}
private static boolean isLinkBaseServerRelative(final String linkBase) {
return linkBase.startsWith("~/");
}
private static Map<String,List<Object>> resolveParameters(
final Configuration configuration, final IProcessingContext processingContext,
final LinkExpression expression, final IStandardVariableExpressionEvaluator expressionEvaluator,
final StandardExpressionExecutionContext expContext) {
final AssignationSequence assignationValues = expression.getParameters();
final Map<String,List<Object>> parameters = new LinkedHashMap<String,List<Object>>(assignationValues.size() + 1, 1.0f);
for (final Assignation assignationValue : assignationValues) {
final Expression parameterNameExpr = assignationValue.getLeft();
final Expression parameterValueExpr = assignationValue.getRight();
// We know parameterNameExpr cannot be null (the Assignation class would not allow it)
final Object parameterNameValue =
Expression.execute(configuration, processingContext, parameterNameExpr, expressionEvaluator, expContext);
final String parameterName =
(parameterNameValue == null? null : parameterNameValue.toString());
if (StringUtils.isEmptyOrWhitespace(parameterName)) {
throw new TemplateProcessingException(
"Parameters in link expression \"" + expression.getStringRepresentation() + "\" are " +
"incorrect: parameter name expression \"" + parameterNameExpr.getStringRepresentation() +
"\" evaluated as null or empty string.");
}
List<Object> currentParameterValues = parameters.get(parameterName);
if (currentParameterValues == null) {
currentParameterValues = new ArrayList<Object>(4);
parameters.put(parameterName, currentParameterValues);
}
if (parameterValueExpr == null) {
// If this is null, it means we want to render the parameter without a value and
// also without an equals sign.
currentParameterValues.add(URL_PARAM_NO_VALUE);
} else {
final Object value =
Expression.execute(configuration, processingContext, parameterValueExpr, expressionEvaluator, expContext);
if (value == null) {
// Not the same as not specifying a value!
currentParameterValues.add("");
} else {
currentParameterValues.addAll(convertParameterValueToList(LiteralValue.unwrap(value)));
}
}
}
return parameters;
}
private static List<Object> convertParameterValueToList(final Object parameterValue) {
if (parameterValue instanceof Iterable<?>) {
final List<Object> result = new ArrayList<Object>(4);
for (final Object obj : (Iterable<?>) parameterValue) {
result.add(obj);
}
return result;
} else if (parameterValue.getClass().isArray()){
final List<Object> result = new ArrayList<Object>(4);
if (parameterValue instanceof byte[]) {
for (final byte obj : (byte[]) parameterValue) {
result.add(Byte.valueOf(obj));
}
} else if (parameterValue instanceof short[]) {
for (final short obj : (short[]) parameterValue) {
result.add(Short.valueOf(obj));
}
} else if (parameterValue instanceof int[]) {
for (final int obj : (int[]) parameterValue) {
result.add(Integer.valueOf(obj));
}
} else if (parameterValue instanceof long[]) {
for (final long obj : (long[]) parameterValue) {
result.add(Long.valueOf(obj));
}
} else if (parameterValue instanceof float[]) {
for (final float obj : (float[]) parameterValue) {
result.add(Float.valueOf(obj));
}
} else if (parameterValue instanceof double[]) {
for (final double obj : (double[]) parameterValue) {
result.add(Double.valueOf(obj));
}
} else if (parameterValue instanceof boolean[]) {
for (final boolean obj : (boolean[]) parameterValue) {
result.add(Boolean.valueOf(obj));
}
} else if (parameterValue instanceof char[]) {
for (final char obj : (char[]) parameterValue) {
result.add(Character.valueOf(obj));
}
} else {
final Object[] objParameterValue = (Object[]) parameterValue;
Collections.addAll(result, objParameterValue);
}
return result;
} else{
return Collections.singletonList(parameterValue);
}
}
}
| true | true | static Object executeLink(final Configuration configuration,
final IProcessingContext processingContext, final LinkExpression expression,
final IStandardVariableExpressionEvaluator expressionEvaluator,
final StandardExpressionExecutionContext expContext) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Evaluating link: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation());
}
final Expression baseExpression = expression.getBase();
Object base =
Expression.execute(configuration, processingContext, baseExpression, expressionEvaluator, expContext);
base = LiteralValue.unwrap(base);
if (base == null || !(base instanceof String) || StringUtils.isEmptyOrWhitespace((String) base)) {
throw new TemplateProcessingException(
"Base for link URL creation must be a non-null and non-empty String " +
"(currently: " + (base == null? null : base.getClass().getName()) + ")");
}
String linkBase = (String) base;
if (!isWebContext(processingContext.getContext()) && !isLinkBaseAbsolute(linkBase) && !isLinkBaseServerRelative(linkBase)) {
throw new TemplateProcessingException(
"Link base \"" + linkBase + "\" cannot be context relative (/) or page relative unless you implement the " +
IWebContext.class.getName() + " interface (context is of class: " +
processingContext.getContext().getClass().getName() + ")");
}
@SuppressWarnings("unchecked")
final Map<String,List<Object>> parameters =
(expression.hasParameters()?
resolveParameters(configuration, processingContext, expression, expressionEvaluator, expContext) :
(Map<String,List<Object>>) Collections.EMPTY_MAP);
/*
* Detect URL fragments (selectors after '#') so that they can be output at the end of
* the URL, after parameters.
*/
final int hashPosition = linkBase.indexOf('#');
String urlFragment = "";
// If hash position == 0 we will not consider it as marking an
// URL fragment.
if (hashPosition > 0) {
// URL fragment String will include the # sign
urlFragment = linkBase.substring(hashPosition);
linkBase = linkBase.substring(0, hashPosition);
}
/*
* Check for the existence of a question mark symbol in the link base itself
*/
final int questionMarkPosition = linkBase.indexOf('?');
final StringBuilder parametersBuilder = new StringBuilder();
for (final Map.Entry<String,List<Object>> parameterEntry : parameters.entrySet()) {
final String parameterName = parameterEntry.getKey();
final List<Object> parameterValues = parameterEntry.getValue();
for (final Object parameterObjectValue : parameterValues) {
// Insert a separator with the previous parameter, if needed
if (parametersBuilder.length() == 0) {
if (questionMarkPosition == -1) {
parametersBuilder.append("?");
} else {
parametersBuilder.append("&");
}
} else {
parametersBuilder.append("&");
}
final String parameterValue =
(parameterObjectValue == null? "" : parameterObjectValue.toString());
if (URL_PARAM_NO_VALUE.equals(parameterValue)) {
// This is a parameter without a value and even without an "=" symbol
parametersBuilder.append(parameterName);
} else {
try {
parametersBuilder.append(parameterName).append("=").append(URLEncoder.encode(parameterValue, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new TemplateProcessingException("Exception while processing link parameters", e);
}
}
}
}
/*
* Context is not web: URLs can only be absolute or server-relative
*/
if (!isWebContext(processingContext.getContext())) {
if (isLinkBaseAbsolute(linkBase)) {
return linkBase + parametersBuilder + urlFragment;
}
// isLinkBaseServerRelative(linkBase) == true
return linkBase.substring(1) + parametersBuilder + urlFragment;
}
/*
* Context is web
*/
final IWebContext webContext = (IWebContext) processingContext.getContext();
final HttpServletRequest request = webContext.getHttpServletRequest();
final HttpServletResponse response = webContext.getHttpServletResponse();
String url = null;
if (isLinkBaseContextRelative(linkBase)) {
url = request.getContextPath() + linkBase + parametersBuilder + urlFragment;
} else if (isLinkBaseServerRelative(linkBase)) {
// remove the "~" from the link base
url = linkBase.substring(1) + parametersBuilder + urlFragment;
} else if (isLinkBaseAbsolute(linkBase)) {
url = linkBase + parametersBuilder + urlFragment;
} else {
// Link base is current-URL-relative
url = linkBase + parametersBuilder + urlFragment;
}
return (response != null? response.encodeURL(url) : url);
}
| static Object executeLink(final Configuration configuration,
final IProcessingContext processingContext, final LinkExpression expression,
final IStandardVariableExpressionEvaluator expressionEvaluator,
final StandardExpressionExecutionContext expContext) {
if (logger.isTraceEnabled()) {
logger.trace("[THYMELEAF][{}] Evaluating link: \"{}\"", TemplateEngine.threadIndex(), expression.getStringRepresentation());
}
final Expression baseExpression = expression.getBase();
Object base =
Expression.execute(configuration, processingContext, baseExpression, expressionEvaluator, expContext);
base = LiteralValue.unwrap(base);
if (base != null && !(base instanceof String)) {
base = base.toString();
}
if (base == null || StringUtils.isEmptyOrWhitespace((String) base)) {
base = "";
}
String linkBase = (String) base;
if (!isWebContext(processingContext.getContext()) && !isLinkBaseAbsolute(linkBase) && !isLinkBaseServerRelative(linkBase)) {
throw new TemplateProcessingException(
"Link base \"" + linkBase + "\" cannot be context relative (/) or page relative unless you implement the " +
IWebContext.class.getName() + " interface (context is of class: " +
processingContext.getContext().getClass().getName() + ")");
}
@SuppressWarnings("unchecked")
final Map<String,List<Object>> parameters =
(expression.hasParameters()?
resolveParameters(configuration, processingContext, expression, expressionEvaluator, expContext) :
(Map<String,List<Object>>) Collections.EMPTY_MAP);
/*
* Detect URL fragments (selectors after '#') so that they can be output at the end of
* the URL, after parameters.
*/
final int hashPosition = linkBase.indexOf('#');
String urlFragment = "";
// If hash position == 0 we will not consider it as marking an
// URL fragment.
if (hashPosition > 0) {
// URL fragment String will include the # sign
urlFragment = linkBase.substring(hashPosition);
linkBase = linkBase.substring(0, hashPosition);
}
/*
* Check for the existence of a question mark symbol in the link base itself
*/
final int questionMarkPosition = linkBase.indexOf('?');
final StringBuilder parametersBuilder = new StringBuilder();
for (final Map.Entry<String,List<Object>> parameterEntry : parameters.entrySet()) {
final String parameterName = parameterEntry.getKey();
final List<Object> parameterValues = parameterEntry.getValue();
for (final Object parameterObjectValue : parameterValues) {
// Insert a separator with the previous parameter, if needed
if (parametersBuilder.length() == 0) {
if (questionMarkPosition == -1) {
parametersBuilder.append("?");
} else {
parametersBuilder.append("&");
}
} else {
parametersBuilder.append("&");
}
final String parameterValue =
(parameterObjectValue == null? "" : parameterObjectValue.toString());
if (URL_PARAM_NO_VALUE.equals(parameterValue)) {
// This is a parameter without a value and even without an "=" symbol
parametersBuilder.append(parameterName);
} else {
try {
parametersBuilder.append(parameterName).append("=").append(URLEncoder.encode(parameterValue, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new TemplateProcessingException("Exception while processing link parameters", e);
}
}
}
}
/*
* Context is not web: URLs can only be absolute or server-relative
*/
if (!isWebContext(processingContext.getContext())) {
if (isLinkBaseAbsolute(linkBase)) {
return linkBase + parametersBuilder + urlFragment;
}
// isLinkBaseServerRelative(linkBase) == true
return linkBase.substring(1) + parametersBuilder + urlFragment;
}
/*
* Context is web
*/
final IWebContext webContext = (IWebContext) processingContext.getContext();
final HttpServletRequest request = webContext.getHttpServletRequest();
final HttpServletResponse response = webContext.getHttpServletResponse();
String url = null;
if (isLinkBaseContextRelative(linkBase)) {
url = request.getContextPath() + linkBase + parametersBuilder + urlFragment;
} else if (isLinkBaseServerRelative(linkBase)) {
// remove the "~" from the link base
url = linkBase.substring(1) + parametersBuilder + urlFragment;
} else if (isLinkBaseAbsolute(linkBase)) {
url = linkBase + parametersBuilder + urlFragment;
} else {
// Link base is current-URL-relative
url = linkBase + parametersBuilder + urlFragment;
}
return (response != null? response.encodeURL(url) : url);
}
|
diff --git a/src/cytoscape/actions/NewWindowSelectedNodesEdgesAction.java b/src/cytoscape/actions/NewWindowSelectedNodesEdgesAction.java
index 2b73a08ca..1f3cb02d1 100644
--- a/src/cytoscape/actions/NewWindowSelectedNodesEdgesAction.java
+++ b/src/cytoscape/actions/NewWindowSelectedNodesEdgesAction.java
@@ -1,126 +1,126 @@
/*
File: NewWindowSelectedNodesEdgesAction.java
Copyright (c) 2006, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
//-------------------------------------------------------------------------
// $Revision$
// $Date$
// $Author$
//-------------------------------------------------------------------------
package cytoscape.actions;
import cytoscape.CyNetwork;
import cytoscape.Cytoscape;
import cytoscape.util.CyNetworkNaming;
import cytoscape.util.CytoscapeAction;
import cytoscape.view.CyNetworkView;
//-------------------------------------------------------------------------
import java.awt.event.ActionEvent;
import java.util.Set;
import javax.swing.event.MenuEvent;
//-------------------------------------------------------------------------
/**
*
*/
public class NewWindowSelectedNodesEdgesAction extends CytoscapeAction {
/**
* Creates a new NewWindowSelectedNodesEdgesAction object.
*/
public NewWindowSelectedNodesEdgesAction() {
super("From selected nodes, selected edges");
setPreferredMenu("File.New.Network");
setAcceleratorCombo(java.awt.event.KeyEvent.VK_N,
ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK);
}
/**
* DOCUMENT ME!
*
* @param e DOCUMENT ME!
*/
public void actionPerformed(ActionEvent e) {
// save the vizmapper catalog
CyNetwork current_network = Cytoscape.getCurrentNetwork();
if ((current_network == null) || (current_network == Cytoscape.getNullNetwork()))
return;
Set nodes = current_network.getSelectedNodes();
Set edges = current_network.getSelectedEdges();
CyNetwork new_network = Cytoscape.createNetwork(nodes, edges,
CyNetworkNaming.getSuggestedSubnetworkTitle(current_network),
current_network);
String title = " selection";
Cytoscape.createNetworkView(new_network, title);
// Set visual style
Cytoscape.getNetworkView(new_network.getIdentifier())
.setVisualStyle(Cytoscape.getCurrentNetworkView().getVisualStyle().getName());
}
public void menuSelected(MenuEvent e) {
CyNetwork n = Cytoscape.getCurrentNetwork();
if ( n == null || n == Cytoscape.getNullNetwork() ) {
setEnabled(false);
return;
}
CyNetworkView v = Cytoscape.getCurrentNetworkView();
if ( v == null || v == Cytoscape.getNullNetworkView() ) {
setEnabled(false);
return;
}
java.util.List edges = v.getSelectedEdges();
java.util.List nodes = v.getSelectedNodes();
- if ( ( nodes != null && nodes.size() > 0 ) &&
+ if ( ( nodes != null && nodes.size() > 0 ) ||
( edges != null && edges.size() > 0 ) )
setEnabled(true);
else
setEnabled(false);
}
}
| true | true | public void menuSelected(MenuEvent e) {
CyNetwork n = Cytoscape.getCurrentNetwork();
if ( n == null || n == Cytoscape.getNullNetwork() ) {
setEnabled(false);
return;
}
CyNetworkView v = Cytoscape.getCurrentNetworkView();
if ( v == null || v == Cytoscape.getNullNetworkView() ) {
setEnabled(false);
return;
}
java.util.List edges = v.getSelectedEdges();
java.util.List nodes = v.getSelectedNodes();
if ( ( nodes != null && nodes.size() > 0 ) &&
( edges != null && edges.size() > 0 ) )
setEnabled(true);
else
setEnabled(false);
}
| public void menuSelected(MenuEvent e) {
CyNetwork n = Cytoscape.getCurrentNetwork();
if ( n == null || n == Cytoscape.getNullNetwork() ) {
setEnabled(false);
return;
}
CyNetworkView v = Cytoscape.getCurrentNetworkView();
if ( v == null || v == Cytoscape.getNullNetworkView() ) {
setEnabled(false);
return;
}
java.util.List edges = v.getSelectedEdges();
java.util.List nodes = v.getSelectedNodes();
if ( ( nodes != null && nodes.size() > 0 ) ||
( edges != null && edges.size() > 0 ) )
setEnabled(true);
else
setEnabled(false);
}
|
diff --git a/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java b/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java
index 36cbff5..ab631e8 100644
--- a/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java
+++ b/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java
@@ -1,110 +1,110 @@
/*
* #%L
* servo
* %%
* Copyright (C) 2011 - 2012 Netflix
* %%
* 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.
* #L%
*/
package com.netflix.servo.publish;
import com.google.common.base.Preconditions;
import com.google.common.io.Closeables;
import com.netflix.servo.Metric;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/**
* Writes observations to a file. The format is a basic text file with tabs
* separating the fields.
*/
public final class FileMetricObserver extends BaseMetricObserver {
private static final Logger LOGGER =
LoggerFactory.getLogger(FileMetricObserver.class);
private static final String FILE_DATE_FORMAT = "yyyy_dd_MM_HH_mm_ss_SSS";
private static final String ISO_DATE_FORMAT = "yyyy-dd-MM'T'HH:mm:ss.SSS";
private final File dir;
private final SimpleDateFormat fileFormat;
private final SimpleDateFormat isoFormat;
/**
* Creates a new instance that stores files in {@code dir} with a prefix of
* {@code name} and a suffix of a timestamp in the format
* {@code yyyy_dd_MM_HH_mm_ss_SSS}.
*
* @param name name to use as a prefix on files
* @param dir directory where observations will be stored
*/
public FileMetricObserver(String name, File dir) {
this(name, String.format("'%s'_%s'.log'", name, FILE_DATE_FORMAT), dir);
}
/**
* Creates a new instance that stores files in {@code dir} with a name that
* is created using {@code namePattern}.
*
* @param name name of the observer
* @param namePattern date format pattern used to create the file names
* @param dir directory where observations will be stored
*/
public FileMetricObserver(String name, String namePattern, File dir) {
super(name);
this.dir = dir;
fileFormat = new SimpleDateFormat(namePattern);
fileFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
isoFormat = new SimpleDateFormat(ISO_DATE_FORMAT);
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
/** {@inheritDoc} */
public void updateImpl(List<Metric> metrics) {
Preconditions.checkNotNull(metrics);
File file = new File(dir, fileFormat.format(new Date()));
Writer out = null;
try {
- LOGGER.debug("writing %d metrics to file %s", metrics.size(), file);
+ LOGGER.debug("writing {} metrics to file {}", metrics.size(), file);
OutputStream fileOut = new FileOutputStream(file, true);
out = new OutputStreamWriter(fileOut, "UTF-8");
for (Metric m : metrics) {
String timestamp = isoFormat.format(new Date(m.getTimestamp()));
out.append(m.getConfig().getName()).append('\t')
.append(m.getConfig().getTags().toString()).append('\t')
.append(timestamp).append('\t')
.append(m.getValue().toString()).append('\n');
}
} catch (IOException e) {
incrementFailedCount();
LOGGER.error("failed to write update to file " + file, e);
} finally {
Closeables.closeQuietly(out);
}
}
}
| true | true | public void updateImpl(List<Metric> metrics) {
Preconditions.checkNotNull(metrics);
File file = new File(dir, fileFormat.format(new Date()));
Writer out = null;
try {
LOGGER.debug("writing %d metrics to file %s", metrics.size(), file);
OutputStream fileOut = new FileOutputStream(file, true);
out = new OutputStreamWriter(fileOut, "UTF-8");
for (Metric m : metrics) {
String timestamp = isoFormat.format(new Date(m.getTimestamp()));
out.append(m.getConfig().getName()).append('\t')
.append(m.getConfig().getTags().toString()).append('\t')
.append(timestamp).append('\t')
.append(m.getValue().toString()).append('\n');
}
} catch (IOException e) {
incrementFailedCount();
LOGGER.error("failed to write update to file " + file, e);
} finally {
Closeables.closeQuietly(out);
}
}
| public void updateImpl(List<Metric> metrics) {
Preconditions.checkNotNull(metrics);
File file = new File(dir, fileFormat.format(new Date()));
Writer out = null;
try {
LOGGER.debug("writing {} metrics to file {}", metrics.size(), file);
OutputStream fileOut = new FileOutputStream(file, true);
out = new OutputStreamWriter(fileOut, "UTF-8");
for (Metric m : metrics) {
String timestamp = isoFormat.format(new Date(m.getTimestamp()));
out.append(m.getConfig().getName()).append('\t')
.append(m.getConfig().getTags().toString()).append('\t')
.append(timestamp).append('\t')
.append(m.getValue().toString()).append('\n');
}
} catch (IOException e) {
incrementFailedCount();
LOGGER.error("failed to write update to file " + file, e);
} finally {
Closeables.closeQuietly(out);
}
}
|
diff --git a/req-proxy/src/main/java/ru/yandex/semantic_geo/freebase/FreebaseObject.java b/req-proxy/src/main/java/ru/yandex/semantic_geo/freebase/FreebaseObject.java
index 714714e..da295e2 100644
--- a/req-proxy/src/main/java/ru/yandex/semantic_geo/freebase/FreebaseObject.java
+++ b/req-proxy/src/main/java/ru/yandex/semantic_geo/freebase/FreebaseObject.java
@@ -1,55 +1,55 @@
package ru.yandex.semantic_geo.freebase;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by IntelliJ IDEA.
* User: rasifiel
* Date: 06.10.12
* Time: 14:38
*/
public class FreebaseObject {
public final String text;
public final String mid;
public final String img_url;
public final JSONObject attrs;
public FreebaseObject(final String text, final String mid, final String img_url, final JSONObject attrs) {
this.text = text;
this.mid = mid;
this.img_url = img_url;
this.attrs = attrs;
}
@Override
public String toString() {
try {
return "FreebaseObject{" +
"text='" + text + '\'' +
", mid='" + mid + '\'' +
", img_url='" + img_url + '\'' +
", attrs=" + attrs.toString(1) +
'}';
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public JSONObject toJson() {
try {
JSONObject res = new JSONObject().put("text", text).put("mid", mid);
if (img_url != null) {
res.put("image", "http://img.freebase.com/api/trans/image_thumb" + img_url +
- "?maxheight=200&mode=fit&maxwidth=150,");
+ "?maxheight=200&mode=fit&maxwidth=150");
}
res.put("attrs", attrs);
FreebaseAPI.mid2url(res);
return res;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
| true | true | public JSONObject toJson() {
try {
JSONObject res = new JSONObject().put("text", text).put("mid", mid);
if (img_url != null) {
res.put("image", "http://img.freebase.com/api/trans/image_thumb" + img_url +
"?maxheight=200&mode=fit&maxwidth=150,");
}
res.put("attrs", attrs);
FreebaseAPI.mid2url(res);
return res;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
| public JSONObject toJson() {
try {
JSONObject res = new JSONObject().put("text", text).put("mid", mid);
if (img_url != null) {
res.put("image", "http://img.freebase.com/api/trans/image_thumb" + img_url +
"?maxheight=200&mode=fit&maxwidth=150");
}
res.put("attrs", attrs);
FreebaseAPI.mid2url(res);
return res;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/okapi/steps/codeshandling/src/main/java/net/sf/okapi/steps/codesremoval/Parameters.java b/okapi/steps/codeshandling/src/main/java/net/sf/okapi/steps/codesremoval/Parameters.java
index 4178ce35c..3cdc25731 100644
--- a/okapi/steps/codeshandling/src/main/java/net/sf/okapi/steps/codesremoval/Parameters.java
+++ b/okapi/steps/codeshandling/src/main/java/net/sf/okapi/steps/codesremoval/Parameters.java
@@ -1,138 +1,138 @@
/*===========================================================================
Copyright (C) 2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.steps.codesremoval;
import net.sf.okapi.common.BaseParameters;
import net.sf.okapi.common.EditorFor;
import net.sf.okapi.common.ParametersDescription;
import net.sf.okapi.common.uidescription.EditorDescription;
import net.sf.okapi.common.uidescription.IEditorDescriptionProvider;
import net.sf.okapi.common.uidescription.ListSelectionPart;
@EditorFor(Parameters.class)
public class Parameters extends BaseParameters implements IEditorDescriptionProvider {
public static final int REMOVECODE_KEEPCONTENT = 0;
public static final int KEEPCODE_REMOVECONTENT = 1;
public static final int REMOVECODE_REMOVECONTENT = 2;
private static final String STRIPSOURCE = "stripSource";
private static final String STRIPTARGET = "stripTarget";
private static final String MODE = "mode";
private static final String INCLUDENONTRANSLATABLE = "includeNonTranslatable";
private boolean stripSource;
private boolean stripTarget;
private int mode;
private boolean includeNonTranslatable;
public Parameters () {
reset();
}
public boolean getStripSource () {
return stripSource;
}
public void setStripSource (boolean stripSource) {
this.stripSource = stripSource;
}
public boolean getStripTarget () {
return stripTarget;
}
public void setStripTarget (boolean stripTarget) {
this.stripTarget = stripTarget;
}
public int getMode () {
return mode;
}
public void setMode (int mode) {
this.mode = mode;
}
public boolean getIncludeNonTranslatable () {
return includeNonTranslatable;
}
public void setIncludeNonTranslatable (boolean includeNonTranslatable) {
this.includeNonTranslatable = includeNonTranslatable;
}
public void reset() {
stripSource = true;
stripTarget = true;
mode = REMOVECODE_REMOVECONTENT;
includeNonTranslatable = true;
}
public void fromString (String data) {
reset();
buffer.fromString(data);
stripSource = buffer.getBoolean(STRIPSOURCE, stripSource);
stripTarget = buffer.getBoolean(STRIPTARGET, stripTarget);
mode = buffer.getInteger(MODE, mode);
includeNonTranslatable = buffer.getBoolean(INCLUDENONTRANSLATABLE, includeNonTranslatable);
}
@Override
public String toString() {
buffer.reset();
buffer.setBoolean(STRIPSOURCE, stripSource);
buffer.setBoolean(STRIPTARGET, stripTarget);
buffer.setInteger(MODE, mode);
buffer.setBoolean(INCLUDENONTRANSLATABLE, includeNonTranslatable);
return buffer.toString();
}
@Override
public ParametersDescription getParametersDescription () {
ParametersDescription desc = new ParametersDescription(this);
desc.add(MODE, "What to remove", "Select what parts of the inline codes to remove");
desc.add(STRIPSOURCE, "Strip codes in the source text", null);
desc.add(STRIPTARGET, "Strip codes in the target text", null);
desc.add(INCLUDENONTRANSLATABLE, "Apply to non-translatable text units", null);
return desc;
}
public EditorDescription createEditorDescription (ParametersDescription paramDesc) {
EditorDescription desc = new EditorDescription("Codes Removal", true, false);
String[] values = {"0", "1", "2"};
String[] labels = {
- "Remove code marker, but keep code content (\"<ph id='1'>[X]</ph>\" ==> \"[X]\")",
- "Remove code content, but keep code marker (\"<ph id='1'>[X]</ph>\" ==> \"<ph id='1'/>\")",
- "Remove code marker and code content (\"<ph id='1'>[X]</ph>\" ==> \"\")",
+ "Remove code marker, but keep code content (\"<ph x='1'>[X]</ph>\" ==> \"[X]\")",
+ "Remove code content, but keep code marker (\"<ph x='1'>[X]</ph>\" ==> \"<ph x='1'/>\")",
+ "Remove code marker and code content (\"<ph x='1'>[X]</ph>\" ==> \"\")",
};
ListSelectionPart lsp = desc.addListSelectionPart(paramDesc.get(MODE), values);
lsp.setChoicesLabels(labels);
desc.addCheckboxPart(paramDesc.get(STRIPSOURCE));
desc.addCheckboxPart(paramDesc.get(STRIPTARGET));
desc.addCheckboxPart(paramDesc.get(INCLUDENONTRANSLATABLE));
return desc;
}
}
| true | true | public EditorDescription createEditorDescription (ParametersDescription paramDesc) {
EditorDescription desc = new EditorDescription("Codes Removal", true, false);
String[] values = {"0", "1", "2"};
String[] labels = {
"Remove code marker, but keep code content (\"<ph id='1'>[X]</ph>\" ==> \"[X]\")",
"Remove code content, but keep code marker (\"<ph id='1'>[X]</ph>\" ==> \"<ph id='1'/>\")",
"Remove code marker and code content (\"<ph id='1'>[X]</ph>\" ==> \"\")",
};
ListSelectionPart lsp = desc.addListSelectionPart(paramDesc.get(MODE), values);
lsp.setChoicesLabels(labels);
desc.addCheckboxPart(paramDesc.get(STRIPSOURCE));
desc.addCheckboxPart(paramDesc.get(STRIPTARGET));
desc.addCheckboxPart(paramDesc.get(INCLUDENONTRANSLATABLE));
return desc;
}
| public EditorDescription createEditorDescription (ParametersDescription paramDesc) {
EditorDescription desc = new EditorDescription("Codes Removal", true, false);
String[] values = {"0", "1", "2"};
String[] labels = {
"Remove code marker, but keep code content (\"<ph x='1'>[X]</ph>\" ==> \"[X]\")",
"Remove code content, but keep code marker (\"<ph x='1'>[X]</ph>\" ==> \"<ph x='1'/>\")",
"Remove code marker and code content (\"<ph x='1'>[X]</ph>\" ==> \"\")",
};
ListSelectionPart lsp = desc.addListSelectionPart(paramDesc.get(MODE), values);
lsp.setChoicesLabels(labels);
desc.addCheckboxPart(paramDesc.get(STRIPSOURCE));
desc.addCheckboxPart(paramDesc.get(STRIPTARGET));
desc.addCheckboxPart(paramDesc.get(INCLUDENONTRANSLATABLE));
return desc;
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/JsfJspJbide1704Test.java b/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/JsfJspJbide1704Test.java
index 55ae71753..cab5978ac 100644
--- a/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/JsfJspJbide1704Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.ui.test/src/org/jboss/tools/jsf/jsp/ca/test/JsfJspJbide1704Test.java
@@ -1,112 +1,113 @@
package org.jboss.tools.jsf.jsp.ca.test;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.FindReplaceDocumentAdapter;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.wst.sse.ui.internal.contentassist.CustomCompletionProposal;
import org.jboss.tools.common.base.test.contentassist.CATestUtil;
import org.jboss.tools.jst.jsp.contentassist.AutoContentAssistantProposal;
import org.jboss.tools.jst.jsp.test.ca.ContentAssistantTestCase;
import org.jboss.tools.test.util.TestProjectProvider;
public class JsfJspJbide1704Test extends ContentAssistantTestCase {
TestProjectProvider provider = null;
boolean makeCopy = false;
private static final String PROJECT_NAME = "JsfJbide1704Test";
private static final String PAGE_NAME = "/WebContent/pages/greeting";
public static Test suite() {
return new TestSuite(JsfJspJbide1704Test.class);
}
public void setUp() throws Exception {
provider = new TestProjectProvider("org.jboss.tools.jsf.ui.test", null, PROJECT_NAME, makeCopy);
project = provider.getProject();
}
protected void tearDown() throws Exception {
if(provider != null) {
provider.dispose();
}
}
public void testJspJbide1704 () {
assertTrue("Test project \"" + PROJECT_NAME + "\" is not loaded", (project != null));
doTestJsfJspJbide1704(PAGE_NAME + ".jsp");
}
public void testXhtmlJbide1704 () {
assertTrue("Test project \"" + PROJECT_NAME + "\" is not loaded", (project != null));
doTestJsfJspJbide1704(PAGE_NAME + ".xhtml");
}
private static final String TEST_RESOURCES_VALUE = "\"resources\"";
private void doTestJsfJspJbide1704(String pageName) {
openEditor(pageName);
try {
final IRegion reg = new FindReplaceDocumentAdapter(document).find(0,
" var=\"msg\"", true, true, false, false);
String text = document.get();
// String errorMessage = null;
List<ICompletionProposal> res = CATestUtil.collectProposals(contentAssistant, viewer, reg.getOffset());
assertTrue("Content Assist returned no proposals: ", (res != null && res.size() > 0));
for (ICompletionProposal proposal : res) {
// There should not be a proposal of type AutoContentAssistantProposal in the result
// (the only exclusion is EL-proposals)
if (proposal instanceof AutoContentAssistantProposal) {
- if(((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("#{")) {
+ if(((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("#{") ||
+ ((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("${")) {
// The only EL template proposal is allowed to be shown here
continue;
}
}
if (proposal instanceof CustomCompletionProposal) {
// There are two cases are allowed to be shown
// AutoContentAssistantProposal which returns the "resources" string as replacement
// CustomCompletionProposal which returns the current value string as replacement
if (!(proposal instanceof AutoContentAssistantProposal)) {
int equalSignIndex = text.lastIndexOf('=', reg.getOffset());
if (equalSignIndex != -1) {
String prevAttrValue = text.substring(equalSignIndex+1, reg.getOffset()).trim();
if (((CustomCompletionProposal)proposal).getReplacementString().equals(prevAttrValue)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
} else {
if (((CustomCompletionProposal)proposal).getReplacementString().equals(TEST_RESOURCES_VALUE)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
}
assertFalse("Content Assistant peturned proposals of type (" + proposal.getClass().getName() + ").", (proposal instanceof AutoContentAssistantProposal));
}
} catch (BadLocationException e) {
fail(e.getMessage());
}
closeEditor();
}
}
| true | true | private void doTestJsfJspJbide1704(String pageName) {
openEditor(pageName);
try {
final IRegion reg = new FindReplaceDocumentAdapter(document).find(0,
" var=\"msg\"", true, true, false, false);
String text = document.get();
// String errorMessage = null;
List<ICompletionProposal> res = CATestUtil.collectProposals(contentAssistant, viewer, reg.getOffset());
assertTrue("Content Assist returned no proposals: ", (res != null && res.size() > 0));
for (ICompletionProposal proposal : res) {
// There should not be a proposal of type AutoContentAssistantProposal in the result
// (the only exclusion is EL-proposals)
if (proposal instanceof AutoContentAssistantProposal) {
if(((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("#{")) {
// The only EL template proposal is allowed to be shown here
continue;
}
}
if (proposal instanceof CustomCompletionProposal) {
// There are two cases are allowed to be shown
// AutoContentAssistantProposal which returns the "resources" string as replacement
// CustomCompletionProposal which returns the current value string as replacement
if (!(proposal instanceof AutoContentAssistantProposal)) {
int equalSignIndex = text.lastIndexOf('=', reg.getOffset());
if (equalSignIndex != -1) {
String prevAttrValue = text.substring(equalSignIndex+1, reg.getOffset()).trim();
if (((CustomCompletionProposal)proposal).getReplacementString().equals(prevAttrValue)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
} else {
if (((CustomCompletionProposal)proposal).getReplacementString().equals(TEST_RESOURCES_VALUE)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
}
assertFalse("Content Assistant peturned proposals of type (" + proposal.getClass().getName() + ").", (proposal instanceof AutoContentAssistantProposal));
}
} catch (BadLocationException e) {
fail(e.getMessage());
}
closeEditor();
}
| private void doTestJsfJspJbide1704(String pageName) {
openEditor(pageName);
try {
final IRegion reg = new FindReplaceDocumentAdapter(document).find(0,
" var=\"msg\"", true, true, false, false);
String text = document.get();
// String errorMessage = null;
List<ICompletionProposal> res = CATestUtil.collectProposals(contentAssistant, viewer, reg.getOffset());
assertTrue("Content Assist returned no proposals: ", (res != null && res.size() > 0));
for (ICompletionProposal proposal : res) {
// There should not be a proposal of type AutoContentAssistantProposal in the result
// (the only exclusion is EL-proposals)
if (proposal instanceof AutoContentAssistantProposal) {
if(((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("#{") ||
((AutoContentAssistantProposal)proposal).getReplacementString().startsWith("${")) {
// The only EL template proposal is allowed to be shown here
continue;
}
}
if (proposal instanceof CustomCompletionProposal) {
// There are two cases are allowed to be shown
// AutoContentAssistantProposal which returns the "resources" string as replacement
// CustomCompletionProposal which returns the current value string as replacement
if (!(proposal instanceof AutoContentAssistantProposal)) {
int equalSignIndex = text.lastIndexOf('=', reg.getOffset());
if (equalSignIndex != -1) {
String prevAttrValue = text.substring(equalSignIndex+1, reg.getOffset()).trim();
if (((CustomCompletionProposal)proposal).getReplacementString().equals(prevAttrValue)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
} else {
if (((CustomCompletionProposal)proposal).getReplacementString().equals(TEST_RESOURCES_VALUE)){
// The old value for the attribute is allowed to be shown here
continue;
}
}
}
assertFalse("Content Assistant peturned proposals of type (" + proposal.getClass().getName() + ").", (proposal instanceof AutoContentAssistantProposal));
}
} catch (BadLocationException e) {
fail(e.getMessage());
}
closeEditor();
}
|
diff --git a/src/com/android/launcher2/Launcher.java b/src/com/android/launcher2/Launcher.java
index 8c73c294..4ae9c7d2 100644
--- a/src/com/android/launcher2/Launcher.java
+++ b/src/com/android/launcher2/Launcher.java
@@ -1,3815 +1,3815 @@
/*
* 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.launcher2;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.SearchManager;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.os.SystemClock;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.text.Selection;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.TextKeyListener;
import android.util.Log;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Advanceable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.common.Search;
import com.android.launcher.R;
import com.android.launcher2.DropTarget.DragObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Default launcher application.
*/
public final class Launcher extends Activity
implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
View.OnTouchListener {
static final String TAG = "Launcher";
static final boolean LOGD = false;
static final boolean PROFILE_STARTUP = false;
static final boolean DEBUG_WIDGETS = false;
static final boolean DEBUG_STRICT_MODE = false;
private static final int MENU_GROUP_WALLPAPER = 1;
private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
private static final int REQUEST_CREATE_SHORTCUT = 1;
private static final int REQUEST_CREATE_APPWIDGET = 5;
private static final int REQUEST_PICK_APPLICATION = 6;
private static final int REQUEST_PICK_SHORTCUT = 7;
private static final int REQUEST_PICK_APPWIDGET = 9;
private static final int REQUEST_PICK_WALLPAPER = 10;
private static final int REQUEST_BIND_APPWIDGET = 11;
static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
static final int SCREEN_COUNT = 5;
static final int DEFAULT_SCREEN = 2;
private static final String PREFERENCES = "launcher.preferences";
static final String FORCE_ENABLE_ROTATION_PROPERTY = "debug.force_enable_rotation";
static final String DUMP_STATE_PROPERTY = "debug.dumpstate";
// The Intent extra that defines whether to ignore the launch animation
static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
"com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
// Type: int
private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
// Type: int
private static final String RUNTIME_STATE = "launcher.state";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
// Type: boolean
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
// Type: long
private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
// Type: int
private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
// Type: parcelable
private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_search_icon";
private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
"com.android.launcher.toolbar_voice_search_icon";
/** The different states that Launcher can be in. */
private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
private State mState = State.WORKSPACE;
private AnimatorSet mStateAnimation;
private AnimatorSet mDividerAnimator;
static final int APPWIDGET_HOST_ID = 1024;
private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
private static final int SHOW_CLING_DURATION = 550;
private static final int DISMISS_CLING_DURATION = 250;
private static final Object sLock = new Object();
private static int sScreen = DEFAULT_SCREEN;
// How long to wait before the new-shortcut animation automatically pans the workspace
private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
private final BroadcastReceiver mCloseSystemDialogsReceiver
= new CloseSystemDialogsIntentReceiver();
private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
private LayoutInflater mInflater;
private Workspace mWorkspace;
private View mQsbDivider;
private View mDockDivider;
private DragLayer mDragLayer;
private DragController mDragController;
private AppWidgetManager mAppWidgetManager;
private LauncherAppWidgetHost mAppWidgetHost;
private ItemInfo mPendingAddInfo = new ItemInfo();
private AppWidgetProviderInfo mPendingAddWidgetInfo;
private int[] mTmpAddItemCellCoordinates = new int[2];
private FolderInfo mFolderInfo;
private Hotseat mHotseat;
private View mAllAppsButton;
private SearchDropTargetBar mSearchDropTargetBar;
private AppsCustomizeTabHost mAppsCustomizeTabHost;
private AppsCustomizePagedView mAppsCustomizeContent;
private boolean mAutoAdvanceRunning = false;
private Bundle mSavedState;
// We set the state in both onCreate and then onNewIntent in some cases, which causes both
// scroll issues (because the workspace may not have been measured yet) and extra work.
// Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
private State mOnResumeState = State.NONE;
private SpannableStringBuilder mDefaultKeySsb = null;
private boolean mWorkspaceLoading = true;
private boolean mPaused = true;
private boolean mRestoring;
private boolean mWaitingForResult;
private boolean mOnResumeNeedsLoad;
// Keep track of whether the user has left launcher
private static boolean sPausedFromUserAction = false;
private Bundle mSavedInstanceState;
private LauncherModel mModel;
private IconCache mIconCache;
private boolean mUserPresent = true;
private boolean mVisible = false;
private boolean mAttached = false;
private static LocaleConfiguration sLocaleConfiguration = null;
private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
private Intent mAppMarketIntent = null;
// Related to the auto-advancing of widgets
private final int ADVANCE_MSG = 1;
private final int mAdvanceInterval = 20000;
private final int mAdvanceStagger = 250;
private long mAutoAdvanceSentTime;
private long mAutoAdvanceTimeLeft = -1;
private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
new HashMap<View, AppWidgetProviderInfo>();
// Determines how long to wait after a rotation before restoring the screen orientation to
// match the sensor state.
private final int mRestoreScreenOrientationDelay = 500;
// External icons saved in case of resource changes, orientation, etc.
private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
static final ArrayList<String> sDumpLogs = new ArrayList<String>();
// We only want to get the SharedPreferences once since it does an FS stat each time we get
// it from the context.
private SharedPreferences mSharedPrefs;
// Holds the page that we need to animate to, and the icon views that we need to animate up
// when we scroll to that page on resume.
private int mNewShortcutAnimatePage = -1;
private ArrayList<View> mNewShortcutAnimateViews = new ArrayList<View>();
private ImageView mFolderIconImageView;
private Bitmap mFolderIconBitmap;
private Canvas mFolderIconCanvas;
private Rect mRectForFolderAnimation = new Rect();
private BubbleTextView mWaitingForResume;
private Runnable mBuildLayersRunnable = new Runnable() {
public void run() {
if (mWorkspace != null) {
mWorkspace.buildPageHardwareLayers();
}
}
};
private static ArrayList<PendingAddArguments> sPendingAddList
= new ArrayList<PendingAddArguments>();
private static class PendingAddArguments {
int requestCode;
Intent intent;
long container;
int screen;
int cellX;
int cellY;
}
private boolean doesFileExist(String filename) {
FileInputStream fis = null;
try {
fis = openFileInput(filename);
fis.close();
return true;
} catch (java.io.FileNotFoundException e) {
return false;
} catch (java.io.IOException e) {
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if (DEBUG_STRICT_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate(savedInstanceState);
LauncherApplication app = ((LauncherApplication)getApplication());
mSharedPrefs = getSharedPreferences(LauncherApplication.getSharedPreferencesKey(),
Context.MODE_PRIVATE);
mModel = app.setLauncher(this);
mIconCache = app.getIconCache();
mDragController = new DragController(this);
mInflater = getLayoutInflater();
mAppWidgetManager = AppWidgetManager.getInstance(this);
mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
mAppWidgetHost.startListening();
// If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
// this also ensures that any synchronous binding below doesn't re-trigger another
// LauncherModel load.
mPaused = false;
if (PROFILE_STARTUP) {
android.os.Debug.startMethodTracing(
Environment.getExternalStorageDirectory() + "/launcher");
}
checkForLocaleChange();
setContentView(R.layout.launcher);
setupViews();
showFirstRunWorkspaceCling();
registerContentObservers();
lockAllApps();
mSavedState = savedInstanceState;
restoreState(mSavedState);
// Update customization drawer _after_ restoring the states
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
if (PROFILE_STARTUP) {
android.os.Debug.stopMethodTracing();
}
if (!mRestoring) {
if (sPausedFromUserAction) {
// If the user leaves launcher, then we should just load items asynchronously when
// they return.
mModel.startLoader(true, -1);
} else {
// We only load the page synchronously if the user rotates (or triggers a
// configuration change) while launcher is in the foreground
mModel.startLoader(true, mWorkspace.getCurrentPage());
}
}
if (!mModel.isAllAppsLoaded()) {
ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent();
mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent);
}
// For handling default keys
mDefaultKeySsb = new SpannableStringBuilder();
Selection.setSelection(mDefaultKeySsb, 0);
IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mCloseSystemDialogsReceiver, filter);
updateGlobalIcons();
// On large interfaces, we want the screen to auto-rotate based on the current orientation
unlockScreenOrientation(true);
}
protected void onUserLeaveHint() {
super.onUserLeaveHint();
sPausedFromUserAction = true;
}
private void updateGlobalIcons() {
boolean searchVisible = false;
boolean voiceVisible = false;
// If we have a saved version of these external icons, we load them up immediately
int coi = getCurrentOrientationIndexForGlobalIcons();
if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
sAppMarketIcon[coi] == null) {
updateAppMarketIcon();
searchVisible = updateGlobalSearchIcon();
voiceVisible = updateVoiceSearchIcon(searchVisible);
}
if (sGlobalSearchIcon[coi] != null) {
updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
searchVisible = true;
}
if (sVoiceSearchIcon[coi] != null) {
updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
voiceVisible = true;
}
if (sAppMarketIcon[coi] != null) {
updateAppMarketIcon(sAppMarketIcon[coi]);
}
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
private void checkForLocaleChange() {
if (sLocaleConfiguration == null) {
new AsyncTask<Void, Void, LocaleConfiguration>() {
@Override
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
@Override
protected void onPostExecute(LocaleConfiguration result) {
sLocaleConfiguration = result;
checkForLocaleChange(); // recursive, but now with a locale configuration
}
}.execute();
return;
}
final Configuration configuration = getResources().getConfiguration();
final String previousLocale = sLocaleConfiguration.locale;
final String locale = configuration.locale.toString();
final int previousMcc = sLocaleConfiguration.mcc;
final int mcc = configuration.mcc;
final int previousMnc = sLocaleConfiguration.mnc;
final int mnc = configuration.mnc;
boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
if (localeChanged) {
sLocaleConfiguration.locale = locale;
sLocaleConfiguration.mcc = mcc;
sLocaleConfiguration.mnc = mnc;
mIconCache.flush();
final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
new Thread("WriteLocaleConfiguration") {
@Override
public void run() {
writeConfiguration(Launcher.this, localeConfiguration);
}
}.start();
}
}
private static class LocaleConfiguration {
public String locale;
public int mcc = -1;
public int mnc = -1;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
DataOutputStream out = null;
try {
out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
out.writeUTF(configuration.locale);
out.writeInt(configuration.mcc);
out.writeInt(configuration.mnc);
out.flush();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
//noinspection ResultOfMethodCallIgnored
context.getFileStreamPath(PREFERENCES).delete();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public DragLayer getDragLayer() {
return mDragLayer;
}
boolean isDraggingEnabled() {
// We prevent dragging when we are loading the workspace as it is possible to pick up a view
// that is subsequently removed from the workspace in startBinding().
return !mModel.isLoadingWorkspace();
}
static int getScreen() {
synchronized (sLock) {
return sScreen;
}
}
static void setScreen(int screen) {
synchronized (sLock) {
sScreen = screen;
}
}
/**
* Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
* a configuration step, this allows the proper animations to run after other transitions.
*/
private boolean completeAdd(PendingAddArguments args) {
boolean result = false;
switch (args.requestCode) {
case REQUEST_PICK_APPLICATION:
completeAddApplication(args.intent, args.container, args.screen, args.cellX,
args.cellY);
break;
case REQUEST_PICK_SHORTCUT:
processShortcut(args.intent);
break;
case REQUEST_CREATE_SHORTCUT:
completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
args.cellY);
result = true;
break;
case REQUEST_CREATE_APPWIDGET:
int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
completeAddAppWidget(appWidgetId, args.container, args.screen, null, null);
result = true;
break;
case REQUEST_PICK_WALLPAPER:
// We just wanted the activity result here so we can clear mWaitingForResult
break;
}
// Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
// if you turned the screen off and then back while in All Apps, Launcher would not
// return to the workspace. Clearing mAddInfo.container here fixes this issue
resetAddInfo();
return result;
}
@Override
protected void onActivityResult(
final int requestCode, final int resultCode, final Intent data) {
if (requestCode == REQUEST_BIND_APPWIDGET) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (resultCode == RESULT_CANCELED) {
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else if (resultCode == RESULT_OK) {
addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
}
return;
}
boolean delayExitSpringLoadedMode = false;
boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
requestCode == REQUEST_CREATE_APPWIDGET);
mWaitingForResult = false;
// We have special handling for widgets
if (isWidgetDrop) {
int appWidgetId = data != null ?
data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
if (appWidgetId < 0) {
Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
"widget configuration activity.");
completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
} else {
completeTwoStageWidgetDrop(resultCode, appWidgetId);
}
return;
}
// The pattern used here is that a user PICKs a specific application,
// which, depending on the target, might need to CREATE the actual target.
// For example, the user would PICK_SHORTCUT for "Music playlist", and we
// launch over to the Music app to actually CREATE_SHORTCUT.
if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
final PendingAddArguments args = new PendingAddArguments();
args.requestCode = requestCode;
args.intent = data;
args.container = mPendingAddInfo.container;
args.screen = mPendingAddInfo.screen;
args.cellX = mPendingAddInfo.cellX;
args.cellY = mPendingAddInfo.cellY;
if (isWorkspaceLocked()) {
sPendingAddList.add(args);
} else {
delayExitSpringLoadedMode = completeAdd(args);
}
}
mDragLayer.clearAnimatedView();
// Exit spring loaded mode if necessary after cancelling the configuration of a widget
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
null);
}
private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
CellLayout cellLayout =
(CellLayout) mWorkspace.getChildAt(mPendingAddInfo.screen);
Runnable onCompleteRunnable = null;
int animationType = 0;
AppWidgetHostView boundWidget = null;
if (resultCode == RESULT_OK) {
animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
mPendingAddWidgetInfo);
boundWidget = layout;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
mPendingAddInfo.screen, layout, null);
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
} else if (resultCode == RESULT_CANCELED) {
animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
onCompleteRunnable = new Runnable() {
@Override
public void run() {
exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
null);
}
};
}
if (mDragLayer.getAnimatedView() != null) {
mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
(DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
animationType, boundWidget, true);
} else {
// The animated view may be null in the case of a rotation during widget configuration
onCompleteRunnable.run();
}
}
@Override
protected void onResume() {
super.onResume();
// Restore the previous launcher state
if (mOnResumeState == State.WORKSPACE) {
showWorkspace(false);
} else if (mOnResumeState == State.APPS_CUSTOMIZE) {
showAllApps(false);
}
mOnResumeState = State.NONE;
// Process any items that were added while Launcher was away
InstallShortcutReceiver.flushInstallQueue(this);
mPaused = false;
sPausedFromUserAction = false;
if (mRestoring || mOnResumeNeedsLoad) {
mWorkspaceLoading = true;
mModel.startLoader(true, -1);
mRestoring = false;
mOnResumeNeedsLoad = false;
}
// Reset the pressed state of icons that were locked in the press state while activities
// were launching
if (mWaitingForResume != null) {
// Resets the previous workspace icon press state
mWaitingForResume.setStayPressed(false);
}
if (mAppsCustomizeContent != null) {
// Resets the previous all apps icon press state
mAppsCustomizeContent.resetDrawableState();
}
// It is possible that widgets can receive updates while launcher is not in the foreground.
// Consequently, the widgets will be inflated in the orientation of the foreground activity
// (framework issue). On resuming, we ensure that any widgets are inflated for the current
// orientation.
getWorkspace().reinflateWidgetsIfNecessary();
// Again, as with the above scenario, it's possible that one or more of the global icons
// were updated in the wrong orientation.
updateGlobalIcons();
}
@Override
protected void onPause() {
// NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
// to be consistent. So re-enable the flag here, and we will re-disable it as necessary
// when Launcher resumes and we are still in AllApps.
updateWallpaperVisibility(true);
super.onPause();
mPaused = true;
mDragController.cancelDrag();
mDragController.resetLastGestureUpTime();
}
@Override
public Object onRetainNonConfigurationInstance() {
// Flag the loader to stop early before switching
mModel.stopLoader();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.surrender();
}
return Boolean.TRUE;
}
// We can't hide the IME if it was forced open. So don't bother
/*
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
WindowManager.LayoutParams lp = getWindow().getAttributes();
inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
android.os.Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
}
});
Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
}
}
*/
private boolean acceptFilter() {
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
return !inputManager.isFullscreenMode();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
final int uniChar = event.getUnicodeChar();
final boolean handled = super.onKeyDown(keyCode, event);
final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
if (!handled && acceptFilter() && isKeyNotWhitespace) {
boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
keyCode, event);
if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
// something usable has been typed - start a search
// the typed text will be retrieved and cleared by
// showSearchDialog()
// If there are multiple keystrokes before the search dialog takes focus,
// onSearchRequested() will be called for every keystroke,
// but it is idempotent, so it's fine.
return onSearchRequested();
}
}
// Eat the long press event so the keyboard doesn't come up.
if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
return true;
}
return handled;
}
private String getTypedText() {
return mDefaultKeySsb.toString();
}
private void clearTypedText() {
mDefaultKeySsb.clear();
mDefaultKeySsb.clearSpans();
Selection.setSelection(mDefaultKeySsb, 0);
}
/**
* Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
* State
*/
private static State intToState(int stateOrdinal) {
State state = State.WORKSPACE;
final State[] stateValues = State.values();
for (int i = 0; i < stateValues.length; i++) {
if (stateValues[i].ordinal() == stateOrdinal) {
state = stateValues[i];
break;
}
}
return state;
}
/**
* Restores the previous state, if it exists.
*
* @param savedState The previous state.
*/
private void restoreState(Bundle savedState) {
if (savedState == null) {
return;
}
State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
if (state == State.APPS_CUSTOMIZE) {
mOnResumeState = State.APPS_CUSTOMIZE;
}
int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
if (currentScreen > -1) {
mWorkspace.setCurrentPage(currentScreen);
}
final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
mPendingAddInfo.container = pendingAddContainer;
mPendingAddInfo.screen = pendingAddScreen;
mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
mWaitingForResult = true;
mRestoring = true;
}
boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
if (renameFolder) {
long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
mFolderInfo = mModel.getFolderById(this, sFolders, id);
mRestoring = true;
}
// Restore the AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String curTab = savedState.getString("apps_customize_currentTab");
if (curTab != null) {
mAppsCustomizeTabHost.setContentTypeImmediate(
mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
mAppsCustomizeContent.loadAssociatedPages(
mAppsCustomizeContent.getCurrentPage());
}
int currentIndex = savedState.getInt("apps_customize_currentIndex");
mAppsCustomizeContent.restorePageForIndex(currentIndex);
}
}
/**
* Finds all the views we need and configure them properly.
*/
private void setupViews() {
final DragController dragController = mDragController;
mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
mQsbDivider = (ImageView) findViewById(R.id.qsb_divider);
mDockDivider = (ImageView) findViewById(R.id.dock_divider);
// Setup the drag layer
mDragLayer.setup(this, dragController);
// Setup the hotseat
mHotseat = (Hotseat) findViewById(R.id.hotseat);
if (mHotseat != null) {
mHotseat.setup(this);
}
// Setup the workspace
mWorkspace.setHapticFeedbackEnabled(false);
mWorkspace.setOnLongClickListener(this);
mWorkspace.setup(dragController);
dragController.addDragListener(mWorkspace);
// Get the search/delete bar
mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
// Setup AppsCustomize
mAppsCustomizeTabHost = (AppsCustomizeTabHost)
findViewById(R.id.apps_customize_pane);
mAppsCustomizeContent = (AppsCustomizePagedView)
mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
mAppsCustomizeContent.setup(this, dragController);
// Setup the drag controller (drop targets have to be added in reverse order in priority)
dragController.setDragScoller(mWorkspace);
dragController.setScrollView(mDragLayer);
dragController.setMoveTarget(mWorkspace);
dragController.addDropTarget(mWorkspace);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.setup(this, dragController);
}
}
/**
* Creates a view representing a shortcut.
*
* @param info The data structure describing the shortcut.
*
* @return A View inflated from R.layout.application.
*/
View createShortcut(ShortcutInfo info) {
return createShortcut(R.layout.application,
(ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
}
/**
* Creates a view representing a shortcut inflated from the specified resource.
*
* @param layoutResId The id of the XML layout used to create the shortcut.
* @param parent The group the shortcut belongs to.
* @param info The data structure describing the shortcut.
*
* @return A View inflated from layoutResId.
*/
View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
favorite.applyFromShortcutInfo(info, mIconCache);
favorite.setOnClickListener(this);
return favorite;
}
/**
* Add an application shortcut to the workspace.
*
* @param data The intent describing the application.
* @param cellInfo The position on screen where to create the shortcut.
*/
void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
final int[] cellXY = mTmpAddItemCellCoordinates;
final CellLayout layout = getCellLayout(container, screen);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
} else if (!layout.findCellForSpan(cellXY, 1, 1)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
if (info != null) {
info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
info.container = ItemInfo.NO_ID;
mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
isWorkspaceLocked(), cellX, cellY);
} else {
Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
}
}
/**
* Add a shortcut to the workspace.
*
* @param data The intent describing the shortcut.
* @param cellInfo The position on screen where to create the shortcut.
*/
private void completeAddShortcut(Intent data, long container, int screen, int cellX,
int cellY) {
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
CellLayout layout = getCellLayout(container, screen);
boolean foundCellSpan = false;
ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
if (info == null) {
return;
}
final View view = createShortcut(info);
// First we check if we already know the exact location where we want to add this item.
if (cellX >= 0 && cellY >= 0) {
cellXY[0] = cellX;
cellXY[1] = cellY;
foundCellSpan = true;
// If appropriate, either create a folder or add to an existing folder
if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
true, null,null)) {
return;
}
DragObject dragObject = new DragObject();
dragObject.dragInfo = info;
if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
true)) {
return;
}
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
}
if (!foundCellSpan) {
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
LauncherModel.addItemToDatabase(this, info, container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
isWorkspaceLocked());
}
}
static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
int minHeight) {
Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
// We want to account for the extra amount of padding that we are adding to the widget
// to ensure that it gets the full amount of space that it has requested
int requiredWidth = minWidth + padding.left + padding.right;
int requiredHeight = minHeight + padding.top + padding.bottom;
return CellLayout.rectToCell(context.getResources(), requiredWidth, requiredHeight, null);
}
static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
}
static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
}
static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
return getSpanForWidget(context, info.componentName, info.minResizeWidth,
info.minResizeHeight);
}
/**
* Add a widget to the workspace.
*
* @param appWidgetId The app widget id
* @param cellInfo The position on screen where to create the widget.
*/
private void completeAddAppWidget(final int appWidgetId, long container, int screen,
AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null) {
appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
}
// Calculate the grid spans needed to fit this widget
CellLayout layout = getCellLayout(container, screen);
int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
int[] spanXY = getSpanForWidget(this, appWidgetInfo);
// Try finding open space on Launcher screen
// We have saved the position to which the widget was dragged-- this really only matters
// if we are placing widgets on a "spring-loaded" screen
int[] cellXY = mTmpAddItemCellCoordinates;
int[] touchXY = mPendingAddInfo.dropPos;
int[] finalSpan = new int[2];
boolean foundCellSpan = false;
if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
cellXY[0] = mPendingAddInfo.cellX;
cellXY[1] = mPendingAddInfo.cellY;
spanXY[0] = mPendingAddInfo.spanX;
spanXY[1] = mPendingAddInfo.spanY;
foundCellSpan = true;
} else if (touchXY != null) {
// when dragging and dropping, just find the closest free spot
int[] result = layout.findNearestVacantArea(
touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
spanXY[1], cellXY, finalSpan);
spanXY[0] = finalSpan[0];
spanXY[1] = finalSpan[1];
foundCellSpan = (result != null);
} else {
foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
}
if (!foundCellSpan) {
if (appWidgetId != -1) {
// Deleting an app widget ID is a void call but writes to disk before returning
// to the caller...
new Thread("deleteAppWidgetId") {
public void run() {
mAppWidgetHost.deleteAppWidgetId(appWidgetId);
}
}.start();
}
showOutOfSpaceMessage(isHotseatLayout(layout));
return;
}
// Build Launcher-specific widget info and save to database
LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
appWidgetInfo.provider);
launcherInfo.spanX = spanXY[0];
launcherInfo.spanY = spanXY[1];
launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
LauncherModel.addItemToDatabase(this, launcherInfo,
container, screen, cellXY[0], cellXY[1], false);
if (!mRestoring) {
if (hostView == null) {
// Perform actual inflation because we're live
launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
} else {
// The AppWidgetHostView has already been inflated and instantiated
launcherInfo.hostView = hostView;
}
launcherInfo.hostView.setTag(launcherInfo);
launcherInfo.hostView.setVisibility(View.VISIBLE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
launcherInfo.notifyWidgetSizeChanged(this);
}
mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
}
resetAddInfo();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mUserPresent = false;
mDragLayer.clearAllResizeFrames();
updateRunning();
// Reset AllApps to its initial state only if we are not in the middle of
// processing a multi-step drop
if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
mAppsCustomizeTabHost.reset();
showWorkspace(false);
}
} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
mUserPresent = true;
updateRunning();
}
}
};
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Listen for broadcasts related to user-presence
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
mAttached = true;
mVisible = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
mVisible = false;
if (mAttached) {
unregisterReceiver(mReceiver);
mAttached = false;
}
updateRunning();
}
public void onWindowVisibilityChanged(int visibility) {
mVisible = visibility == View.VISIBLE;
updateRunning();
// The following code used to be in onResume, but it turns out onResume is called when
// you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
// is a more appropriate event to handle
if (mVisible) {
mAppsCustomizeTabHost.onWindowVisible();
if (!mWorkspaceLoading) {
final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
// We want to let Launcher draw itself at least once before we force it to build
// layers on all the workspace pages, so that transitioning to Launcher from other
// apps is nice and speedy. Usually the first call to preDraw doesn't correspond to
// a true draw so we wait until the second preDraw call to be safe
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
// We delay the layer building a bit in order to give
// other message processing a time to run. In particular
// this avoids a delay in hiding the IME if it was
// currently shown, because doing that may involve
// some communication back with the app.
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
observer.removeOnPreDrawListener(this);
return true;
}
});
}
// When Launcher comes back to foreground, a different Activity might be responsible for
// the app market intent, so refresh the icon
updateAppMarketIcon();
clearTypedText();
}
}
private void sendAdvanceMessage(long delay) {
mHandler.removeMessages(ADVANCE_MSG);
Message msg = mHandler.obtainMessage(ADVANCE_MSG);
mHandler.sendMessageDelayed(msg, delay);
mAutoAdvanceSentTime = System.currentTimeMillis();
}
private void updateRunning() {
boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
if (autoAdvanceRunning != mAutoAdvanceRunning) {
mAutoAdvanceRunning = autoAdvanceRunning;
if (autoAdvanceRunning) {
long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
sendAdvanceMessage(delay);
} else {
if (!mWidgetsToAdvance.isEmpty()) {
mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
(System.currentTimeMillis() - mAutoAdvanceSentTime));
}
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0); // Remove messages sent using postDelayed()
}
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == ADVANCE_MSG) {
int i = 0;
for (View key: mWidgetsToAdvance.keySet()) {
final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
final int delay = mAdvanceStagger * i;
if (v instanceof Advanceable) {
postDelayed(new Runnable() {
public void run() {
((Advanceable) v).advance();
}
}, delay);
}
i++;
}
sendAdvanceMessage(mAdvanceInterval);
}
}
};
void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
if (v instanceof Advanceable) {
mWidgetsToAdvance.put(hostView, appWidgetInfo);
((Advanceable) v).fyiWillBeAdvancedByHostKThx();
updateRunning();
}
}
void removeWidgetToAutoAdvance(View hostView) {
if (mWidgetsToAdvance.containsKey(hostView)) {
mWidgetsToAdvance.remove(hostView);
updateRunning();
}
}
public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
removeWidgetToAutoAdvance(launcherInfo.hostView);
launcherInfo.hostView = null;
}
void showOutOfSpaceMessage(boolean isHotseatLayout) {
int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
}
public LauncherAppWidgetHost getAppWidgetHost() {
return mAppWidgetHost;
}
public LauncherModel getModel() {
return mModel;
}
void closeSystemDialogs() {
getWindow().closeAllPanels();
// Whatever we were doing is hereby canceled.
mWaitingForResult = false;
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// Close the menu
if (Intent.ACTION_MAIN.equals(intent.getAction())) {
// also will cancel mWaitingForResult.
closeSystemDialogs();
boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
!= Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
Folder openFolder = mWorkspace.getOpenFolder();
// In all these cases, only animate if we're already on home
mWorkspace.exitWidgetResizeMode();
if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
openFolder == null) {
mWorkspace.moveToDefaultScreen(true);
}
closeFolder();
exitSpringLoadedDragMode();
// If we are already on home, then just animate back to the workspace, otherwise, just
// wait until onResume to set the state back to Workspace
if (alreadyOnHome) {
showWorkspace(true);
} else {
mOnResumeState = State.WORKSPACE;
}
final View v = getWindow().peekDecorView();
if (v != null && v.getWindowToken() != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// Reset AllApps to its initial state
if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
mAppsCustomizeTabHost.reset();
}
}
}
@Override
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
for (int page: mSynchronouslyBoundPages) {
mWorkspace.restoreInstanceStateForChild(page);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
super.onSaveInstanceState(outState);
outState.putInt(RUNTIME_STATE, mState.ordinal());
// We close any open folder since it will not be re-opened, and we need to make sure
// this state is reflected.
closeFolder();
if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
mWaitingForResult) {
outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
}
if (mFolderInfo != null && mWaitingForResult) {
outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
}
// Save the current AppsCustomize tab
if (mAppsCustomizeTabHost != null) {
String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
if (currentTabTag != null) {
outState.putString("apps_customize_currentTab", currentTabTag);
}
int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
outState.putInt("apps_customize_currentIndex", currentIndex);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove all pending runnables
mHandler.removeMessages(ADVANCE_MSG);
mHandler.removeMessages(0);
mWorkspace.removeCallbacks(mBuildLayersRunnable);
// Stop callbacks from LauncherModel
LauncherApplication app = ((LauncherApplication) getApplication());
mModel.stopLoader();
app.setLauncher(null);
try {
mAppWidgetHost.stopListening();
} catch (NullPointerException ex) {
Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
}
mAppWidgetHost = null;
mWidgetsToAdvance.clear();
TextKeyListener.getInstance().release();
// Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
// to prevent leaking Launcher activities on orientation change.
if (mModel != null) {
mModel.unbindItemInfosAndClearQueuedBindRunnables();
}
getContentResolver().unregisterContentObserver(mWidgetObserver);
unregisterReceiver(mCloseSystemDialogsReceiver);
mDragLayer.clearAllResizeFrames();
((ViewGroup) mWorkspace.getParent()).removeAllViews();
mWorkspace.removeAllViews();
mWorkspace = null;
mDragController = null;
LauncherAnimUtils.onDestroyActivity();
}
public DragController getDragController() {
return mDragController;
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
if (requestCode >= 0) mWaitingForResult = true;
super.startActivityForResult(intent, requestCode);
}
/**
* Indicates that we want global search for this activity by setting the globalSearch
* argument for {@link #startSearch} to true.
*/
@Override
public void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
showWorkspace(true);
if (initialQuery == null) {
// Use any text typed in the launcher as the initial query
initialQuery = getTypedText();
}
if (appSearchData == null) {
appSearchData = new Bundle();
appSearchData.putString(Search.SOURCE, "launcher-search");
}
Rect sourceBounds = new Rect();
if (mSearchDropTargetBar != null) {
sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
}
startGlobalSearch(initialQuery, selectInitialQuery,
appSearchData, sourceBounds);
}
/**
* Starts the global search activity. This code is a copied from SearchManager
*/
public void startGlobalSearch(String initialQuery,
boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
if (globalSearchActivity == null) {
Log.w(TAG, "No global search activity found.");
return;
}
Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(globalSearchActivity);
// Make sure that we have a Bundle to put source in
if (appSearchData == null) {
appSearchData = new Bundle();
} else {
appSearchData = new Bundle(appSearchData);
}
// Set source to package name of app that starts global search, if not set already.
if (!appSearchData.containsKey("source")) {
appSearchData.putString("source", getPackageName());
}
intent.putExtra(SearchManager.APP_DATA, appSearchData);
if (!TextUtils.isEmpty(initialQuery)) {
intent.putExtra(SearchManager.QUERY, initialQuery);
}
if (selectInitialQuery) {
intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
}
intent.setSourceBounds(sourceBounds);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (isWorkspaceLocked()) {
return false;
}
super.onCreateOptionsMenu(menu);
Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
String helpUrl = getString(R.string.help_url);
Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
.setIcon(android.R.drawable.ic_menu_gallery)
.setAlphabeticShortcut('W');
menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
.setIcon(android.R.drawable.ic_menu_manage)
.setIntent(manageApps)
.setAlphabeticShortcut('M');
menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
.setIcon(android.R.drawable.ic_menu_preferences)
.setIntent(settings)
.setAlphabeticShortcut('P');
if (!helpUrl.isEmpty()) {
menu.add(0, MENU_HELP, 0, R.string.menu_help)
.setIcon(android.R.drawable.ic_menu_help)
.setIntent(help)
.setAlphabeticShortcut('H');
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mAppsCustomizeTabHost.isTransitioning()) {
return false;
}
boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_WALLPAPER_SETTINGS:
startWallpaper();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null, true);
// Use a custom animation for launching search
return true;
}
public boolean isWorkspaceLocked() {
return mWorkspaceLoading || mWaitingForResult;
}
private void resetAddInfo() {
mPendingAddInfo.container = ItemInfo.NO_ID;
mPendingAddInfo.screen = -1;
mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
mPendingAddInfo.dropPos = null;
}
void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
AppWidgetProviderInfo appWidgetInfo) {
if (appWidgetInfo.configure != null) {
mPendingAddWidgetInfo = appWidgetInfo;
// Launch over to configure widget, if needed
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
intent.setComponent(appWidgetInfo.configure);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
} else {
// Otherwise just add it
completeAddAppWidget(appWidgetId, info.container, info.screen, boundWidget,
appWidgetInfo);
// Exit spring loaded mode if necessary after adding the widget
exitSpringLoadedDragModeDelayed(true, false, null);
}
}
/**
* Process a shortcut drop.
*
* @param componentName The name of the component
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void processShortcutFromDrop(ComponentName componentName, long container, int screen,
int[] cell, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = container;
mPendingAddInfo.screen = screen;
mPendingAddInfo.dropPos = loc;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
createShortcutIntent.setComponent(componentName);
processShortcut(createShortcutIntent);
}
/**
* Process a widget drop.
*
* @param info The PendingAppWidgetInfo of the widget being added.
* @param screen The screen where it should be added
* @param cell The cell it should be added to, optional
* @param position The location on the screen where it was dropped, optional
*/
void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
int[] cell, int[] span, int[] loc) {
resetAddInfo();
mPendingAddInfo.container = info.container = container;
mPendingAddInfo.screen = info.screen = screen;
mPendingAddInfo.dropPos = loc;
mPendingAddInfo.minSpanX = info.minSpanX;
mPendingAddInfo.minSpanY = info.minSpanY;
if (cell != null) {
mPendingAddInfo.cellX = cell[0];
mPendingAddInfo.cellY = cell[1];
}
if (span != null) {
mPendingAddInfo.spanX = span[0];
mPendingAddInfo.spanY = span[1];
}
AppWidgetHostView hostView = info.boundWidget;
int appWidgetId;
if (hostView != null) {
appWidgetId = hostView.getAppWidgetId();
addAppWidgetImpl(appWidgetId, info, hostView, info.info);
} else {
// In this case, we either need to start an activity to get permission to bind
// the widget, or we need to start an activity to configure the widget, or both.
appWidgetId = getAppWidgetHost().allocateAppWidgetId();
if (mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.componentName)) {
addAppWidgetImpl(appWidgetId, info, null, info.info);
} else {
mPendingAddWidgetInfo = info.info;
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
}
}
}
void processShortcut(Intent intent) {
// Handle case where user selected "Applications"
String applicationName = getResources().getString(R.string.group_applications);
String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
if (applicationName != null && applicationName.equals(shortcutName)) {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
} else {
startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
}
}
void processWallpaper(Intent intent) {
startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
}
FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
int cellY) {
final FolderInfo folderInfo = new FolderInfo();
folderInfo.title = getText(R.string.folder_name);
// Update the model
LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
false);
sFolders.put(folderInfo.id, folderInfo);
// Create the view
FolderIcon newFolder =
FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
isWorkspaceLocked());
return newFolder;
}
void removeFolder(FolderInfo folder) {
sFolders.remove(folder.id);
}
private void startWallpaper() {
showWorkspace(true);
final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
Intent chooser = Intent.createChooser(pickWallpaper,
getText(R.string.chooser_wallpaper));
// NOTE: Adds a configure option to the chooser if the wallpaper supports it
// Removed in Eclair MR1
// WallpaperManager wm = (WallpaperManager)
// getSystemService(Context.WALLPAPER_SERVICE);
// WallpaperInfo wi = wm.getWallpaperInfo();
// if (wi != null && wi.getSettingsActivity() != null) {
// LabeledIntent li = new LabeledIntent(getPackageName(),
// R.string.configure_wallpaper, 0);
// li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
// }
startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
}
/**
* Registers various content observers. The current implementation registers
* only a favorites observer to keep track of the favorites applications.
*/
private void registerContentObservers() {
ContentResolver resolver = getContentResolver();
resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
true, mWidgetObserver);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (doesFileExist(DUMP_STATE_PROPERTY)) {
dumpState();
return true;
}
break;
}
} else if (event.getAction() == KeyEvent.ACTION_UP) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_HOME:
return true;
}
}
return super.dispatchKeyEvent(event);
}
@Override
public void onBackPressed() {
if (isAllAppsVisible()) {
showWorkspace(true);
} else if (mWorkspace.getOpenFolder() != null) {
Folder openFolder = mWorkspace.getOpenFolder();
if (openFolder.isEditingName()) {
openFolder.dismissEditingName();
} else {
closeFolder();
}
} else {
mWorkspace.exitWidgetResizeMode();
// Back button is a no-op here, but give at least some feedback for the button press
mWorkspace.showOutlinesTemporarily();
}
}
/**
* Re-listen when widgets are reset.
*/
private void onAppWidgetReset() {
if (mAppWidgetHost != null) {
mAppWidgetHost.startListening();
}
}
/**
* Launches the intent referred by the clicked shortcut.
*
* @param v The view representing the clicked shortcut.
*/
public void onClick(View v) {
// Make sure that rogue clicks don't get through while allapps is launching, or after the
// view has detached (it's possible for this to happen if the view is removed mid touch).
if (v.getWindowToken() == null) {
return;
}
if (!mWorkspace.isFinishedSwitchingState()) {
return;
}
Object tag = v.getTag();
if (tag instanceof ShortcutInfo) {
// Open shortcut
final Intent intent = ((ShortcutInfo) tag).intent;
int[] pos = new int[2];
v.getLocationOnScreen(pos);
intent.setSourceBounds(new Rect(pos[0], pos[1],
pos[0] + v.getWidth(), pos[1] + v.getHeight()));
boolean success = startActivitySafely(v, intent, tag);
if (success && v instanceof BubbleTextView) {
mWaitingForResume = (BubbleTextView) v;
mWaitingForResume.setStayPressed(true);
}
} else if (tag instanceof FolderInfo) {
if (v instanceof FolderIcon) {
FolderIcon fi = (FolderIcon) v;
handleFolderClick(fi);
}
} else if (v == mAllAppsButton) {
if (isAllAppsVisible()) {
showWorkspace(true);
} else {
onClickAllAppsButton(v);
}
}
}
public boolean onTouch(View v, MotionEvent event) {
// this is an intercepted event being forwarded from mWorkspace;
// clicking anywhere on the workspace causes the customization drawer to slide down
showWorkspace(true);
return false;
}
/**
* Event handler for the search button
*
* @param v The view that was clicked.
*/
public void onClickSearchButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
onSearchRequested();
}
/**
* Event handler for the voice button
*
* @param v The view that was clicked.
*/
public void onClickVoiceButton(View v) {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
try {
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (activityName != null) {
intent.setPackage(activityName.getPackageName());
}
startActivity(null, intent, "onClickVoiceButton");
} catch (ActivityNotFoundException e) {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivitySafely(null, intent, "onClickVoiceButton");
}
}
/**
* Event handler for the "grid" button that appears on the home screen, which
* enters all apps mode.
*
* @param v The view that was clicked.
*/
public void onClickAllAppsButton(View v) {
showAllApps(true);
}
public void onTouchDownAllAppsButton(View v) {
// Provide the same haptic feedback that the system offers for virtual keys.
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
}
public void onClickAppMarketButton(View v) {
if (mAppMarketIntent != null) {
startActivitySafely(v, mAppMarketIntent, "app market");
} else {
Log.e(TAG, "Invalid app market intent.");
}
}
void startApplicationDetailsActivity(ComponentName componentName) {
String packageName = componentName.getPackageName();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", packageName, null));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivitySafely(null, intent, "startApplicationDetailsActivity");
}
void startApplicationUninstallActivity(ApplicationInfo appInfo) {
if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
// System applications cannot be installed. For now, show a toast explaining that.
// We may give them the option of disabling apps this way.
int messageId = R.string.uninstall_system_app_text;
Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
} else {
String packageName = appInfo.componentName.getPackageName();
String className = appInfo.componentName.getClassName();
Intent intent = new Intent(
Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
}
}
boolean startActivity(View v, Intent intent, Object tag) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
// Only launch using the new animation if the shortcut has not opted out (this is a
// private contract between launcher and may be ignored in the future).
boolean useLaunchAnimation = (v != null) &&
!intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
if (useLaunchAnimation) {
ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
v.getMeasuredWidth(), v.getMeasuredHeight());
startActivity(intent, opts.toBundle());
} else {
startActivity(intent);
}
return true;
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity. "
+ "tag="+ tag + " intent=" + intent, e);
}
return false;
}
boolean startActivitySafely(View v, Intent intent, Object tag) {
boolean success = false;
try {
success = startActivity(v, intent, tag);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
}
return success;
}
void startActivityForResultSafely(Intent intent, int requestCode) {
try {
startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Launcher does not have the permission to launch " + intent +
". Make sure to create a MAIN intent-filter for the corresponding activity " +
"or use the exported attribute for this activity.", e);
}
}
private void handleFolderClick(FolderIcon folderIcon) {
final FolderInfo info = folderIcon.getFolderInfo();
Folder openFolder = mWorkspace.getFolderForTag(info);
// If the folder info reports that the associated folder is open, then verify that
// it is actually opened. There have been a few instances where this gets out of sync.
if (info.opened && openFolder == null) {
Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
+ info.screen + " (" + info.cellX + ", " + info.cellY + ")");
info.opened = false;
}
if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
// Close any open folder
closeFolder();
// Open the requested folder
openFolder(folderIcon);
} else {
// Find the open folder...
int folderScreen;
if (openFolder != null) {
folderScreen = mWorkspace.getPageForView(openFolder);
// .. and close it
closeFolder(openFolder);
if (folderScreen != mWorkspace.getCurrentPage()) {
// Close any folder open on the current screen
closeFolder();
// Pull the folder onto this screen
openFolder(folderIcon);
}
}
}
}
/**
* This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
* in the DragLayer in the exact absolute location of the original FolderIcon.
*/
private void copyFolderIconToImage(FolderIcon fi) {
final int width = fi.getMeasuredWidth();
final int height = fi.getMeasuredHeight();
// Lazy load ImageView, Bitmap and Canvas
if (mFolderIconImageView == null) {
mFolderIconImageView = new ImageView(this);
}
if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
mFolderIconBitmap.getHeight() != height) {
mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mFolderIconCanvas = new Canvas(mFolderIconBitmap);
}
DragLayer.LayoutParams lp;
if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
} else {
lp = new DragLayer.LayoutParams(width, height);
}
// The layout from which the folder is being opened may be scaled, adjust the starting
// view size by this scale factor.
float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
lp.customPosition = true;
lp.x = mRectForFolderAnimation.left;
lp.y = mRectForFolderAnimation.top;
lp.width = (int) (scale * width);
lp.height = (int) (scale * height);
mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
fi.draw(mFolderIconCanvas);
mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
if (fi.getFolder() != null) {
mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
}
// Just in case this image view is still in the drag layer from a previous animation,
// we remove it and re-add it.
if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
mDragLayer.removeView(mFolderIconImageView);
}
mDragLayer.addView(mFolderIconImageView, lp);
if (fi.getFolder() != null) {
fi.getFolder().bringToFront();
}
}
private void growAndFadeOutFolderIcon(FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
FolderInfo info = (FolderInfo) fi.getTag();
if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
CellLayout cl = (CellLayout) fi.getParent().getParent();
CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
}
// Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
copyFolderIconToImage(fi);
fi.setVisibility(View.INVISIBLE);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.start();
}
private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
if (fi == null) return;
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
final CellLayout cl = (CellLayout) fi.getParent().getParent();
// We remove and re-draw the FolderIcon in-case it has changed
mDragLayer.removeView(mFolderIconImageView);
copyFolderIconToImage(fi);
ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
scaleX, scaleY);
oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
oa.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (cl != null) {
cl.clearFolderLeaveBehind();
// Remove the ImageView copy of the FolderIcon and make the original visible.
mDragLayer.removeView(mFolderIconImageView);
fi.setVisibility(View.VISIBLE);
}
}
});
oa.start();
}
/**
* Opens the user folder described by the specified tag. The opening of the folder
* is animated relative to the specified View. If the View is null, no animation
* is played.
*
* @param folderInfo The FolderInfo describing the folder to open.
*/
public void openFolder(FolderIcon folderIcon) {
Folder folder = folderIcon.getFolder();
FolderInfo info = folder.mInfo;
info.opened = true;
// Just verify that the folder hasn't already been added to the DragLayer.
// There was a one-off crash where the folder had a parent already.
if (folder.getParent() == null) {
mDragLayer.addView(folder);
mDragController.addDropTarget((DropTarget) folder);
} else {
Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
folder.getParent() + ").");
}
folder.animateOpen();
growAndFadeOutFolderIcon(folderIcon);
}
public void closeFolder() {
Folder folder = mWorkspace.getOpenFolder();
if (folder != null) {
if (folder.isEditingName()) {
folder.dismissEditingName();
}
closeFolder(folder);
// Dismiss the folder cling
dismissFolderCling(null);
}
}
void closeFolder(Folder folder) {
folder.getInfo().opened = false;
ViewGroup parent = (ViewGroup) folder.getParent().getParent();
if (parent != null) {
FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
shrinkAndFadeInFolderIcon(fi);
}
folder.animateClosed();
}
public boolean onLongClick(View v) {
if (!isDraggingEnabled()) return false;
if (isWorkspaceLocked()) return false;
if (mState != State.WORKSPACE) return false;
if (!(v instanceof CellLayout)) {
v = (View) v.getParent().getParent();
}
resetAddInfo();
CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
// This happens when long clicking an item with the dpad/trackball
if (longClickCellInfo == null) {
return true;
}
// The hotseat touch handling does not go through Workspace, and we always allow long press
// on hotseat items.
final View itemUnderLongClick = longClickCellInfo.cell;
boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
if (allowLongPress && !mDragController.isDragging()) {
if (itemUnderLongClick == null) {
// User long pressed on empty space
mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
startWallpaper();
} else {
if (!(itemUnderLongClick instanceof Folder)) {
// User long pressed on an item
mWorkspace.startDrag(longClickCellInfo);
}
}
}
return true;
}
boolean isHotseatLayout(View layout) {
return mHotseat != null && layout != null &&
(layout instanceof CellLayout) && (layout == mHotseat.getLayout());
}
Hotseat getHotseat() {
return mHotseat;
}
SearchDropTargetBar getSearchBar() {
return mSearchDropTargetBar;
}
/**
* Returns the CellLayout of the specified container at the specified screen.
*/
CellLayout getCellLayout(long container, int screen) {
if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
if (mHotseat != null) {
return mHotseat.getLayout();
} else {
return null;
}
} else {
return (CellLayout) mWorkspace.getChildAt(screen);
}
}
Workspace getWorkspace() {
return mWorkspace;
}
// Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
public boolean isAllAppsVisible() {
return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
}
public boolean isAllAppsButtonRank(int rank) {
return mHotseat.isAllAppsButtonRank(rank);
}
/**
* Helper method for the cameraZoomIn/cameraZoomOut animations
* @param view The view being animated
* @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
* @param scaleFactor The scale factor used for the zoom
*/
private void setPivotsForZoom(View view, float scaleFactor) {
view.setPivotX(view.getWidth() / 2.0f);
view.setPivotY(view.getHeight() / 2.0f);
}
void disableWallpaperIfInAllApps() {
// Only disable it if we are in all apps
if (isAllAppsVisible()) {
if (mAppsCustomizeTabHost != null &&
!mAppsCustomizeTabHost.isTransitioning()) {
updateWallpaperVisibility(false);
}
}
}
void updateWallpaperVisibility(boolean visible) {
int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
int curflags = getWindow().getAttributes().flags
& WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
if (wpflags != curflags) {
getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
}
}
private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
}
}
private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 0f);
}
private void dispatchOnLauncherTransitionStep(View v, float t) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
}
}
private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
if (v instanceof LauncherTransitionable) {
((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
}
// Update the workspace transition step as well
dispatchOnLauncherTransitionStep(v, 1f);
}
/**
* Things to test when changing the following seven functions.
* - Home from workspace
* - from center screen
* - from other screens
* - Home from all apps
* - from center screen
* - from other screens
* - Back from all apps
* - from center screen
* - from other screens
* - Launch app from workspace and quit
* - with back
* - with home
* - Launch app from all apps and quit
* - with back
* - with home
* - Go to a screen that's not the default, then all
* apps, and launch and app, and go back
* - with back
* -with home
* - On workspace, long press power and go back
* - with back
* - with home
* - On all apps, long press power and go back
* - with back
* - with home
* - On workspace, power off
* - On all apps, power off
* - Launch an app and turn off the screen while in that app
* - Go back with home key
* - Go back with back key TODO: make this not go to workspace
* - From all apps
* - From workspace
* - Enter and exit car mode (becuase it causes an extra configuration changed)
* - From all apps
* - From the center workspace
* - From another workspace
*/
/**
* Zoom the camera out from the workspace to reveal 'toView'.
* Assumes that the view to show is anchored at either the very top or very bottom
* of the screen.
*/
private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
- if (!springLoaded && !LauncherApplication.isScreenLarge()) {
+ if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
/**
* Zoom the camera back into the workspace, hiding 'fromView'.
* This is the opposite of showAppsCustomizeHelper.
* @param animated If true, the transition will be animated.
*/
private void hideAppsCustomizeHelper(State toState, final boolean animated,
final boolean springLoaded, final Runnable onCompleteRunnable) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
final int fadeOutDuration =
res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
final float scaleFactor = (float)
res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mAppsCustomizeTabHost;
final View toView = mWorkspace;
Animator workspaceAnim = null;
if (toState == State.WORKSPACE) {
int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.NORMAL, animated, stagger);
} else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
workspaceAnim = mWorkspace.getChangeStateAnimation(
Workspace.State.SPRING_LOADED, animated);
}
setPivotsForZoom(fromView, scaleFactor);
updateWallpaperVisibility(true);
showHotseat(animated);
if (animated) {
final LauncherViewPropertyAnimator scaleAnim =
new LauncherViewPropertyAnimator(fromView);
scaleAnim.
scaleX(scaleFactor).scaleY(scaleFactor).
setDuration(duration).
setInterpolator(new Workspace.ZoomInInterpolator());
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(fromView, "alpha", 1f, 0f)
.setDuration(fadeOutDuration);
alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float t = 1f - (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
updateWallpaperVisibility(true);
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
if (mWorkspace != null) {
mWorkspace.hideScrollingIndicator(false);
}
if (onCompleteRunnable != null) {
onCompleteRunnable.run();
}
}
});
mStateAnimation.playTogether(scaleAnim, alphaAnim);
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
final Animator stateAnimation = mStateAnimation;
mWorkspace.post(new Runnable() {
public void run() {
if (stateAnimation != mStateAnimation)
return;
mStateAnimation.start();
}
});
} else {
fromView.setVisibility(View.GONE);
dispatchOnLauncherTransitionPrepare(fromView, animated, true);
dispatchOnLauncherTransitionStart(fromView, animated, true);
dispatchOnLauncherTransitionEnd(fromView, animated, true);
dispatchOnLauncherTransitionPrepare(toView, animated, true);
dispatchOnLauncherTransitionStart(toView, animated, true);
dispatchOnLauncherTransitionEnd(toView, animated, true);
mWorkspace.hideScrollingIndicator(false);
}
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
mAppsCustomizeTabHost.onTrimMemory();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
// When another window occludes launcher (like the notification shade, or recents),
// ensure that we enable the wallpaper flag so that transitions are done correctly.
updateWallpaperVisibility(true);
} else {
// When launcher has focus again, disable the wallpaper if we are in AllApps
mWorkspace.postDelayed(new Runnable() {
@Override
public void run() {
disableWallpaperIfInAllApps();
}
}, 500);
}
}
void showWorkspace(boolean animated) {
showWorkspace(animated, null);
}
void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
if (mState != State.WORKSPACE) {
boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
mWorkspace.setVisibility(View.VISIBLE);
hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
// Show the search bar (only animate if we were showing the drop target bar in spring
// loaded mode)
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
}
// We only need to animate in the dock divider if we're going from spring loaded mode
showDockDivider(animated && wasInSpringLoadedMode);
// Set focus to the AppsCustomize button
if (mAllAppsButton != null) {
mAllAppsButton.requestFocus();
}
}
mWorkspace.flashScrollingIndicator(animated);
// Change the state *after* we've called all the transition code
mState = State.WORKSPACE;
// Resume the auto-advance of widgets
mUserPresent = true;
updateRunning();
// send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void showAllApps(boolean animated) {
if (mState != State.WORKSPACE) return;
showAppsCustomizeHelper(animated, false);
mAppsCustomizeTabHost.requestFocus();
// Change the state *after* we've called all the transition code
mState = State.APPS_CUSTOMIZE;
// Pause the auto-advance of widgets until we are out of AllApps
mUserPresent = false;
updateRunning();
closeFolder();
// Send an accessibility event to announce the context change
getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
void enterSpringLoadedDragMode() {
if (isAllAppsVisible()) {
hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
hideDockDivider();
mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
}
}
void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
final Runnable onCompleteRunnable) {
if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (successfulDrop) {
// Before we show workspace, hide all apps again because
// exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
// clean up our state transition functions
mAppsCustomizeTabHost.setVisibility(View.GONE);
showWorkspace(true, onCompleteRunnable);
} else {
exitSpringLoadedDragMode();
}
}
}, (extendedDelay ?
EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
}
void exitSpringLoadedDragMode() {
if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
final boolean animated = true;
final boolean springLoaded = true;
showAppsCustomizeHelper(animated, springLoaded);
mState = State.APPS_CUSTOMIZE;
}
// Otherwise, we are not in spring loaded mode, so don't do anything.
}
void hideDockDivider() {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.INVISIBLE);
mDockDivider.setVisibility(View.INVISIBLE);
}
}
void showDockDivider(boolean animated) {
if (mQsbDivider != null && mDockDivider != null) {
mQsbDivider.setVisibility(View.VISIBLE);
mDockDivider.setVisibility(View.VISIBLE);
if (mDividerAnimator != null) {
mDividerAnimator.cancel();
mQsbDivider.setAlpha(1f);
mDockDivider.setAlpha(1f);
mDividerAnimator = null;
}
if (animated) {
mDividerAnimator = LauncherAnimUtils.createAnimatorSet();
mDividerAnimator.playTogether(LauncherAnimUtils.ofFloat(mQsbDivider, "alpha", 1f),
LauncherAnimUtils.ofFloat(mDockDivider, "alpha", 1f));
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mDividerAnimator.setDuration(duration);
mDividerAnimator.start();
}
}
}
void lockAllApps() {
// TODO
}
void unlockAllApps() {
// TODO
}
/**
* Shows the hotseat area.
*/
void showHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 1f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionInDuration();
}
mHotseat.animate().alpha(1f).setDuration(duration);
}
} else {
mHotseat.setAlpha(1f);
}
}
}
/**
* Hides the hotseat area.
*/
void hideHotseat(boolean animated) {
if (!LauncherApplication.isScreenLarge()) {
if (animated) {
if (mHotseat.getAlpha() != 0f) {
int duration = 0;
if (mSearchDropTargetBar != null) {
duration = mSearchDropTargetBar.getTransitionOutDuration();
}
mHotseat.animate().alpha(0f).setDuration(duration);
}
} else {
mHotseat.setAlpha(0f);
}
}
}
/**
* Add an item from all apps or customize onto the given workspace screen.
* If layout is null, add to the current screen.
*/
void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
showOutOfSpaceMessage(isHotseatLayout(layout));
}
}
/** Maps the current orientation to an index for referencing orientation correct global icons */
private int getCurrentOrientationIndexForGlobalIcons() {
// default - 0, landscape - 1
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
return 1;
default:
return 0;
}
}
private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
try {
PackageManager packageManager = getPackageManager();
// Look for the toolbar icon specified in the activity meta-data
Bundle metaData = packageManager.getActivityInfo(
activityName, PackageManager.GET_META_DATA).metaData;
if (metaData != null) {
int iconResId = metaData.getInt(resourceName);
if (iconResId != 0) {
Resources res = packageManager.getResourcesForActivity(activityName);
return res.getDrawable(iconResId);
}
}
} catch (NameNotFoundException e) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
" not found", e);
} catch (Resources.NotFoundException nfe) {
// This can happen if the activity defines an invalid drawable
Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
nfe);
}
return null;
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
Resources r = getResources();
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
TextView button = (TextView) findViewById(buttonId);
// If we were unable to find the icon via the meta-data, use a generic one
if (toolbarIcon == null) {
toolbarIcon = r.getDrawable(fallbackDrawableId);
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return null;
} else {
toolbarIcon.setBounds(0, 0, w, h);
if (button != null) {
button.setCompoundDrawables(toolbarIcon, null, null, null);
}
return toolbarIcon.getConstantState();
}
}
// if successful in getting icon, return it; otherwise, set button to use default drawable
private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
int buttonId, ComponentName activityName, int fallbackDrawableId,
String toolbarResourceName) {
ImageView button = (ImageView) findViewById(buttonId);
Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
if (button != null) {
// If we were unable to find the icon via the meta-data, use a
// generic one
if (toolbarIcon == null) {
button.setImageResource(fallbackDrawableId);
} else {
button.setImageDrawable(toolbarIcon);
}
}
return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
}
private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
TextView button = (TextView) findViewById(buttonId);
button.setCompoundDrawables(d, null, null, null);
}
private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
ImageView button = (ImageView) findViewById(buttonId);
button.setImageDrawable(d.newDrawable(getResources()));
}
private void invalidatePressedFocusedStates(View container, View button) {
if (container instanceof HolographicLinearLayout) {
HolographicLinearLayout layout = (HolographicLinearLayout) container;
layout.invalidatePressedFocusedStates();
} else if (button instanceof HolographicImageView) {
HolographicImageView view = (HolographicImageView) button;
view.invalidatePressedFocusedStates();
}
}
private boolean updateGlobalSearchIcon() {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName activityName = searchManager.getGlobalSearchActivity();
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_SEARCH_ICON_METADATA_NAME);
if (sGlobalSearchIcon[coi] == null) {
sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
searchButton.setVisibility(View.VISIBLE);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
return true;
} else {
// We disable both search and voice search when there is no global search provider
if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
searchButton.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.GONE);
}
return false;
}
}
private void updateGlobalSearchIcon(Drawable.ConstantState d) {
final View searchButtonContainer = findViewById(R.id.search_button_container);
final View searchButton = (ImageView) findViewById(R.id.search_button);
updateButtonWithDrawable(R.id.search_button, d);
invalidatePressedFocusedStates(searchButtonContainer, searchButton);
}
private boolean updateVoiceSearchIcon(boolean searchVisible) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
// We only show/update the voice search icon if the search icon is enabled as well
final SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
ComponentName activityName = null;
if (globalSearchActivity != null) {
// Check if the global search activity handles voice search
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setPackage(globalSearchActivity.getPackageName());
activityName = intent.resolveActivity(getPackageManager());
}
if (activityName == null) {
// Fallback: check if an activity other than the global search activity
// resolves this
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
activityName = intent.resolveActivity(getPackageManager());
}
if (searchVisible && activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
if (sVoiceSearchIcon[coi] == null) {
sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
TOOLBAR_ICON_METADATA_NAME);
}
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
voiceButton.setVisibility(View.VISIBLE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.VISIBLE);
}
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
return true;
} else {
if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
voiceButton.setVisibility(View.GONE);
if (voiceButtonProxy != null) {
voiceButtonProxy.setVisibility(View.GONE);
}
return false;
}
}
private void updateVoiceSearchIcon(Drawable.ConstantState d) {
final View voiceButtonContainer = findViewById(R.id.voice_button_container);
final View voiceButton = findViewById(R.id.voice_button);
updateButtonWithDrawable(R.id.voice_button, d);
invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
}
/**
* Sets the app market icon
*/
private void updateAppMarketIcon() {
final View marketButton = findViewById(R.id.market_button);
Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
// Find the app market activity by resolving an intent.
// (If multiple app markets are installed, it will return the ResolverActivity.)
ComponentName activityName = intent.resolveActivity(getPackageManager());
if (activityName != null) {
int coi = getCurrentOrientationIndexForGlobalIcons();
mAppMarketIntent = intent;
sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
TOOLBAR_ICON_METADATA_NAME);
marketButton.setVisibility(View.VISIBLE);
} else {
// We should hide and disable the view so that we don't try and restore the visibility
// of it when we swap between drag & normal states from IconDropTarget subclasses.
marketButton.setVisibility(View.GONE);
marketButton.setEnabled(false);
}
}
private void updateAppMarketIcon(Drawable.ConstantState d) {
// Ensure that the new drawable we are creating has the approprate toolbar icon bounds
Resources r = getResources();
Drawable marketIconDrawable = d.newDrawable(r);
int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
marketIconDrawable.setBounds(0, 0, w, h);
updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
boolean result = super.dispatchPopulateAccessibilityEvent(event);
final List<CharSequence> text = event.getText();
text.clear();
text.add(getString(R.string.home));
return result;
}
/**
* Receives notifications when system dialogs are to be closed.
*/
private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
closeSystemDialogs();
}
}
/**
* Receives notifications whenever the appwidgets are reset.
*/
private class AppWidgetResetObserver extends ContentObserver {
public AppWidgetResetObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
onAppWidgetReset();
}
}
/**
* If the activity is currently paused, signal that we need to re-run the loader
* in onResume.
*
* This needs to be called from incoming places where resources might have been loaded
* while we are paused. That is becaues the Configuration might be wrong
* when we're not running, and if it comes back to what it was when we
* were paused, we are not restarted.
*
* Implementation of the method from LauncherModel.Callbacks.
*
* @return true if we are currently paused. The caller might be able to
* skip some work in that case since we will come back again.
*/
public boolean setLoadOnResume() {
if (mPaused) {
Log.i(TAG, "setLoadOnResume");
mOnResumeNeedsLoad = true;
return true;
} else {
return false;
}
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public int getCurrentWorkspaceScreen() {
if (mWorkspace != null) {
return mWorkspace.getCurrentPage();
} else {
return SCREEN_COUNT / 2;
}
}
/**
* Refreshes the shortcuts shown on the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void startBinding() {
final Workspace workspace = mWorkspace;
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
mWorkspace.clearDropTargets();
int count = workspace.getChildCount();
for (int i = 0; i < count; i++) {
// Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
layoutParent.removeAllViewsInLayout();
}
mWidgetsToAdvance.clear();
if (mHotseat != null) {
mHotseat.resetLayout();
}
}
/**
* Bind the items start-end from the list.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
setLoadOnResume();
// Get the list of added shortcuts and intersect them with the set of shortcuts here
Set<String> newApps = new HashSet<String>();
newApps = mSharedPrefs.getStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, newApps);
Workspace workspace = mWorkspace;
for (int i = start; i < end; i++) {
final ItemInfo item = shortcuts.get(i);
// Short circuit if we are loading dock items for a configuration which has no dock
if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
mHotseat == null) {
continue;
}
switch (item.itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
ShortcutInfo info = (ShortcutInfo) item;
String uri = info.intent.toUri(0).toString();
View shortcut = createShortcut(info);
workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
boolean animateIconUp = false;
synchronized (newApps) {
if (newApps.contains(uri)) {
animateIconUp = newApps.remove(uri);
}
}
if (animateIconUp) {
// Prepare the view to be animated up
shortcut.setAlpha(0f);
shortcut.setScaleX(0f);
shortcut.setScaleY(0f);
mNewShortcutAnimatePage = item.screen;
if (!mNewShortcutAnimateViews.contains(shortcut)) {
mNewShortcutAnimateViews.add(shortcut);
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
(ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
(FolderInfo) item, mIconCache);
workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
item.cellY, 1, 1, false);
break;
}
}
workspace.requestLayout();
}
/**
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindFolders(HashMap<Long, FolderInfo> folders) {
setLoadOnResume();
sFolders.clear();
sFolders.putAll(folders);
}
/**
* Add the views for a widget to the workspace.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppWidget(LauncherAppWidgetInfo item) {
setLoadOnResume();
final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: " + item);
}
final Workspace workspace = mWorkspace;
final int appWidgetId = item.appWidgetId;
final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
if (DEBUG_WIDGETS) {
Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
}
item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
item.hostView.setTag(item);
item.onBindAppWidget(this);
workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
item.cellY, item.spanX, item.spanY, false);
addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
workspace.requestLayout();
if (DEBUG_WIDGETS) {
Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
+ (SystemClock.uptimeMillis()-start) + "ms");
}
}
public void onPageBoundSynchronously(int page) {
mSynchronouslyBoundPages.add(page);
}
/**
* Callback saying that there aren't any more items to bind.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void finishBindingItems() {
setLoadOnResume();
if (mSavedState != null) {
if (!mWorkspace.hasFocus()) {
mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
}
mSavedState = null;
}
mWorkspace.restoreInstanceStateForRemainingPages();
// If we received the result of any pending adds while the loader was running (e.g. the
// widget configuration forced an orientation change), process them now.
for (int i = 0; i < sPendingAddList.size(); i++) {
completeAdd(sPendingAddList.get(i));
}
sPendingAddList.clear();
// Update the market app icon as necessary (the other icons will be managed in response to
// package changes in bindSearchablesChanged()
updateAppMarketIcon();
// Animate up any icons as necessary
if (mVisible || mWorkspaceLoading) {
Runnable newAppsRunnable = new Runnable() {
@Override
public void run() {
runNewAppsAnimation(false);
}
};
boolean willSnapPage = mNewShortcutAnimatePage > -1 &&
mNewShortcutAnimatePage != mWorkspace.getCurrentPage();
if (canRunNewAppsAnimation()) {
// If the user has not interacted recently, then either snap to the new page to show
// the new-apps animation or just run them if they are to appear on the current page
if (willSnapPage) {
mWorkspace.snapToPage(mNewShortcutAnimatePage, newAppsRunnable);
} else {
runNewAppsAnimation(false);
}
} else {
// If the user has interacted recently, then just add the items in place if they
// are on another page (or just normally if they are added to the current page)
runNewAppsAnimation(willSnapPage);
}
}
mWorkspaceLoading = false;
}
private boolean canRunNewAppsAnimation() {
long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
}
/**
* Runs a new animation that scales up icons that were added while Launcher was in the
* background.
*
* @param immediate whether to run the animation or show the results immediately
*/
private void runNewAppsAnimation(boolean immediate) {
AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
Collection<Animator> bounceAnims = new ArrayList<Animator>();
// Order these new views spatially so that they animate in order
Collections.sort(mNewShortcutAnimateViews, new Comparator<View>() {
@Override
public int compare(View a, View b) {
CellLayout.LayoutParams alp = (CellLayout.LayoutParams) a.getLayoutParams();
CellLayout.LayoutParams blp = (CellLayout.LayoutParams) b.getLayoutParams();
int cellCountX = LauncherModel.getCellCountX();
return (alp.cellY * cellCountX + alp.cellX) - (blp.cellY * cellCountX + blp.cellX);
}
});
// Animate each of the views in place (or show them immediately if requested)
if (immediate) {
for (View v : mNewShortcutAnimateViews) {
v.setAlpha(1f);
v.setScaleX(1f);
v.setScaleY(1f);
}
} else {
for (int i = 0; i < mNewShortcutAnimateViews.size(); ++i) {
View v = mNewShortcutAnimateViews.get(i);
ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat("alpha", 1f),
PropertyValuesHolder.ofFloat("scaleX", 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f));
bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
bounceAnims.add(bounceAnim);
}
anim.playTogether(bounceAnims);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mWorkspace.postDelayed(mBuildLayersRunnable, 500);
}
});
anim.start();
}
// Clean up
mNewShortcutAnimatePage = -1;
mNewShortcutAnimateViews.clear();
new Thread("clearNewAppsThread") {
public void run() {
mSharedPrefs.edit()
.putInt(InstallShortcutReceiver.NEW_APPS_PAGE_KEY, -1)
.putStringSet(InstallShortcutReceiver.NEW_APPS_LIST_KEY, null)
.commit();
}
}.start();
}
@Override
public void bindSearchablesChanged() {
boolean searchVisible = updateGlobalSearchIcon();
boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
}
}
/**
* Add the icons for all apps.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
Runnable setAllAppsRunnable = new Runnable() {
public void run() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.setApps(apps);
}
}
};
// Remove the progress bar entirely; we could also make it GONE
// but better to remove it since we know it's not going to be used
View progressBar = mAppsCustomizeTabHost.
findViewById(R.id.apps_customize_progress_bar);
if (progressBar != null) {
((ViewGroup)progressBar.getParent()).removeView(progressBar);
// We just post the call to setApps so the user sees the progress bar
// disappear-- otherwise, it just looks like the progress bar froze
// which doesn't look great
mAppsCustomizeTabHost.post(setAllAppsRunnable);
} else {
// If we did not initialize the spinner in onCreate, then we can directly set the
// list of applications without waiting for any progress bars views to be hidden.
setAllAppsRunnable.run();
}
}
/**
* A package was installed.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.addApps(apps);
}
}
/**
* A package was updated.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
setLoadOnResume();
if (mWorkspace != null) {
mWorkspace.updateShortcuts(apps);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.updateApps(apps);
}
}
/**
* A package was uninstalled.
*
* Implementation of the method from LauncherModel.Callbacks.
*/
public void bindAppsRemoved(ArrayList<String> packageNames, boolean permanent) {
if (permanent) {
mWorkspace.removeItems(packageNames);
}
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.removeApps(packageNames);
}
// Notify the drag controller
mDragController.onAppsRemoved(packageNames, this);
}
/**
* A number of packages were updated.
*/
public void bindPackagesUpdated() {
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.onPackagesUpdated();
}
}
private int mapConfigurationOriActivityInfoOri(int configOri) {
final Display d = getWindowManager().getDefaultDisplay();
int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
switch (d.getRotation()) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
// We are currently in the same basic orientation as the natural orientation
naturalOri = configOri;
break;
case Surface.ROTATION_90:
case Surface.ROTATION_270:
// We are currently in the other basic orientation to the natural orientation
naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
break;
}
int[] oriMap = {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
};
// Since the map starts at portrait, we need to offset if this device's natural orientation
// is landscape.
int indexOffset = 0;
if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
indexOffset = 1;
}
return oriMap[(d.getRotation() + indexOffset) % 4];
}
public boolean isRotationEnabled() {
boolean forceEnableRotation = doesFileExist(FORCE_ENABLE_ROTATION_PROPERTY);
boolean enableRotation = forceEnableRotation ||
getResources().getBoolean(R.bool.allow_rotation);
return enableRotation;
}
public void lockScreenOrientation() {
if (isRotationEnabled()) {
setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
.getConfiguration().orientation));
}
}
public void unlockScreenOrientation(boolean immediate) {
if (isRotationEnabled()) {
if (immediate) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
mHandler.postDelayed(new Runnable() {
public void run() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}, mRestoreScreenOrientationDelay);
}
}
}
/* Cling related */
private boolean isClingsEnabled() {
// disable clings when running in a test harness
if(ActivityManager.isRunningInTestHarness()) return false;
return true;
}
private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
Cling cling = (Cling) findViewById(clingId);
if (cling != null) {
cling.init(this, positionData);
cling.setVisibility(View.VISIBLE);
cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
if (animate) {
cling.buildLayer();
cling.setAlpha(0f);
cling.animate()
.alpha(1f)
.setInterpolator(new AccelerateInterpolator())
.setDuration(SHOW_CLING_DURATION)
.setStartDelay(delay)
.start();
} else {
cling.setAlpha(1f);
}
}
return cling;
}
private void dismissCling(final Cling cling, final String flag, int duration) {
if (cling != null) {
ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
anim.setDuration(duration);
anim.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation) {
cling.setVisibility(View.GONE);
cling.cleanup();
// We should update the shared preferences on a background thread
new Thread("dismissClingThread") {
public void run() {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.putBoolean(flag, true);
editor.commit();
}
}.start();
};
});
anim.start();
}
}
private void removeCling(int id) {
final View cling = findViewById(id);
if (cling != null) {
final ViewGroup parent = (ViewGroup) cling.getParent();
parent.post(new Runnable() {
@Override
public void run() {
parent.removeView(cling);
}
});
}
}
private boolean skipCustomClingIfNoAccounts() {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
if (customCling) {
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.google");
return accounts.length == 0;
}
return false;
}
public void showFirstRunWorkspaceCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
!skipCustomClingIfNoAccounts() ) {
initCling(R.id.workspace_cling, null, false, 0);
} else {
removeCling(R.id.workspace_cling);
}
}
public void showFirstRunAllAppsCling(int[] position) {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
initCling(R.id.all_apps_cling, position, true, 0);
} else {
removeCling(R.id.all_apps_cling);
}
}
public Cling showFirstRunFoldersCling() {
// Enable the clings only if they have not been dismissed before
if (isClingsEnabled() &&
!mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
return initCling(R.id.folder_cling, null, true, 0);
} else {
removeCling(R.id.folder_cling);
return null;
}
}
public boolean isFolderClingVisible() {
Cling cling = (Cling) findViewById(R.id.folder_cling);
if (cling != null) {
return cling.getVisibility() == View.VISIBLE;
}
return false;
}
public void dismissWorkspaceCling(View v) {
Cling cling = (Cling) findViewById(R.id.workspace_cling);
dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissAllAppsCling(View v) {
Cling cling = (Cling) findViewById(R.id.all_apps_cling);
dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
public void dismissFolderCling(View v) {
Cling cling = (Cling) findViewById(R.id.folder_cling);
dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
}
/**
* Prints out out state for debugging.
*/
public void dumpState() {
Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
Log.d(TAG, "mSavedState=" + mSavedState);
Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
Log.d(TAG, "mRestoring=" + mRestoring);
Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
Log.d(TAG, "sFolders.size=" + sFolders.size());
mModel.dumpState();
if (mAppsCustomizeContent != null) {
mAppsCustomizeContent.dumpState();
}
Log.d(TAG, "END launcher2 dump state");
}
@Override
public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
super.dump(prefix, fd, writer, args);
writer.println(" ");
writer.println("Debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
writer.println(" " + sDumpLogs.get(i));
}
}
public static void dumpDebugLogsToConsole() {
Log.d(TAG, "");
Log.d(TAG, "*********************");
Log.d(TAG, "Launcher debug logs: ");
for (int i = 0; i < sDumpLogs.size(); i++) {
Log.d(TAG, " " + sDumpLogs.get(i));
}
Log.d(TAG, "*********************");
Log.d(TAG, "");
}
}
interface LauncherTransitionable {
View getContent();
void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
void onLauncherTransitionStep(Launcher l, float t);
void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
}
| true | true | private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
| private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
if (mStateAnimation != null) {
mStateAnimation.cancel();
mStateAnimation = null;
}
final Resources res = getResources();
final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
final View fromView = mWorkspace;
final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
final int startDelay =
res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
setPivotsForZoom(toView, scale);
// Shrink workspaces away if going to AppsCustomize from workspace
Animator workspaceAnim =
mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
if (animated) {
toView.setScaleX(scale);
toView.setScaleY(scale);
final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
scaleAnim.
scaleX(1f).scaleY(1f).
setDuration(duration).
setInterpolator(new Workspace.ZoomOutInterpolator());
toView.setVisibility(View.VISIBLE);
toView.setAlpha(0f);
final ObjectAnimator alphaAnim = ObjectAnimator
.ofFloat(toView, "alpha", 0f, 1f)
.setDuration(fadeDuration);
alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation == null) {
throw new RuntimeException("animation is null");
}
float t = (Float) animation.getAnimatedValue();
dispatchOnLauncherTransitionStep(fromView, t);
dispatchOnLauncherTransitionStep(toView, t);
}
});
// toView should appear right at the end of the workspace shrink
// animation
mStateAnimation = LauncherAnimUtils.createAnimatorSet();
mStateAnimation.play(scaleAnim).after(startDelay);
mStateAnimation.play(alphaAnim).after(startDelay);
mStateAnimation.addListener(new AnimatorListenerAdapter() {
boolean animationCancelled = false;
@Override
public void onAnimationStart(Animator animation) {
updateWallpaperVisibility(true);
// Prepare the position
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
}
@Override
public void onAnimationEnd(Animator animation) {
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
if (mWorkspace != null && !springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
}
if (!animationCancelled) {
updateWallpaperVisibility(false);
}
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
@Override
public void onAnimationCancel(Animator animation) {
animationCancelled = true;
}
});
if (workspaceAnim != null) {
mStateAnimation.play(workspaceAnim);
}
boolean delayAnim = false;
final ViewTreeObserver observer;
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
// If any of the objects being animated haven't been measured/laid out
// yet, delay the animation until we get a layout pass
if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
(mWorkspace.getMeasuredWidth() == 0) ||
(toView.getMeasuredWidth() == 0)) {
observer = mWorkspace.getViewTreeObserver();
delayAnim = true;
} else {
observer = null;
}
final AnimatorSet stateAnimation = mStateAnimation;
final Runnable startAnimRunnable = new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
setPivotsForZoom(toView, scale);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
toView.post(new Runnable() {
public void run() {
// Check that mStateAnimation hasn't changed while
// we waited for a layout/draw pass
if (mStateAnimation != stateAnimation)
return;
mStateAnimation.start();
}
});
}
};
if (delayAnim) {
final OnGlobalLayoutListener delayedStart = new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toView.post(startAnimRunnable);
observer.removeOnGlobalLayoutListener(this);
}
};
observer.addOnGlobalLayoutListener(delayedStart);
} else {
startAnimRunnable.run();
}
} else {
toView.setTranslationX(0.0f);
toView.setTranslationY(0.0f);
toView.setScaleX(1.0f);
toView.setScaleY(1.0f);
toView.setVisibility(View.VISIBLE);
toView.bringToFront();
if (!springLoaded && !LauncherApplication.isScreenLarge()) {
// Hide the workspace scrollbar
mWorkspace.hideScrollingIndicator(true);
hideDockDivider();
// Hide the search bar
if (mSearchDropTargetBar != null) {
mSearchDropTargetBar.hideSearchBar(false);
}
}
dispatchOnLauncherTransitionPrepare(fromView, animated, false);
dispatchOnLauncherTransitionStart(fromView, animated, false);
dispatchOnLauncherTransitionEnd(fromView, animated, false);
dispatchOnLauncherTransitionPrepare(toView, animated, false);
dispatchOnLauncherTransitionStart(toView, animated, false);
dispatchOnLauncherTransitionEnd(toView, animated, false);
updateWallpaperVisibility(false);
}
}
|
diff --git a/src/minecraft/ljdp/minechem/client/render/item/ItemDecomposerRenderer.java b/src/minecraft/ljdp/minechem/client/render/item/ItemDecomposerRenderer.java
index 6d4f079..bdd328d 100644
--- a/src/minecraft/ljdp/minechem/client/render/item/ItemDecomposerRenderer.java
+++ b/src/minecraft/ljdp/minechem/client/render/item/ItemDecomposerRenderer.java
@@ -1,47 +1,44 @@
package ljdp.minechem.client.render.item;
import ljdp.minechem.client.ModelDecomposer;
import ljdp.minechem.common.utils.ConstantValue;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.item.ItemStack;
public class ItemDecomposerRenderer extends ItemMinechemRenderer {
private ModelDecomposer model;
public ItemDecomposerRenderer() {
model = new ModelDecomposer();
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
String texture = ConstantValue.DECOMPOSER_MODEL_ON;
GL11.glPushMatrix();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
if (type == ItemRenderType.ENTITY) {
GL11.glTranslatef(0.0F, 0.7f, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
GL11.glScalef(0.5f, 0.5f, 0.5f);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
} else if (type == ItemRenderType.EQUIPPED) {
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
}
else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON){
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
}
else {
GL11.glTranslatef(0.0F, 1.0F, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
}
model.render(0.0625F);
GL11.glPopMatrix();
}
}
| false | true | public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
String texture = ConstantValue.DECOMPOSER_MODEL_ON;
GL11.glPushMatrix();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
if (type == ItemRenderType.ENTITY) {
GL11.glTranslatef(0.0F, 0.7f, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
GL11.glScalef(0.5f, 0.5f, 0.5f);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
} else if (type == ItemRenderType.EQUIPPED) {
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
}
else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON){
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
}
else {
GL11.glTranslatef(0.0F, 1.0F, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
}
model.render(0.0625F);
GL11.glPopMatrix();
}
| public void renderItem(ItemRenderType type, ItemStack item, Object... data) {
String texture = ConstantValue.DECOMPOSER_MODEL_ON;
GL11.glPushMatrix();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, FMLClientHandler.instance().getClient().renderEngine.getTexture(texture));
if (type == ItemRenderType.ENTITY) {
GL11.glTranslatef(0.0F, 0.7f, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
GL11.glScalef(0.5f, 0.5f, 0.5f);
} else if (type == ItemRenderType.EQUIPPED) {
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
}
else if (type == ItemRenderType.EQUIPPED_FIRST_PERSON){
GL11.glTranslatef(0.5F, 1.6F, 0.0F);
GL11.glRotatef(180f, -1f, 0f, 1f);
}
else {
GL11.glTranslatef(0.0F, 1.0F, 0.0F);
GL11.glRotatef(180f, 0f, 0f, 1f);
}
model.render(0.0625F);
GL11.glPopMatrix();
}
|
diff --git a/src/core/java/com/edgenius/core/repository/FileNode.java b/src/core/java/com/edgenius/core/repository/FileNode.java
index 9e5a5c4..b818248 100644
--- a/src/core/java/com/edgenius/core/repository/FileNode.java
+++ b/src/core/java/com/edgenius/core/repository/FileNode.java
@@ -1,413 +1,414 @@
/*
* =============================================================
* Copyright (C) 2007-2011 Edgenius (http://www.edgenius.com)
* =============================================================
* License Information: http://www.edgenius.com/licensing/edgenius/2.0/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2.0
* as published by the Free Software Foundation.
*
* 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
*
* http://www.gnu.org/licenses/gpl.txt
*
* ****************************************************************
*/
package com.edgenius.core.repository;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.edgenius.core.Constants;
import com.edgenius.core.model.CrFileNode;
import com.edgenius.core.model.User;
import com.edgenius.core.service.MessageService;
import com.edgenius.core.service.UserReadingService;
import com.edgenius.core.util.DateUtil;
import com.edgenius.core.util.WebUtil;
import com.google.gson.Gson;
public class FileNode implements Serializable{
private static final long serialVersionUID = 4849308949298514211L;
public final static String NAMESPACE = "http://www.geniuswiki.com/geniuswiki";
public static final String PREFIX = "geniuswiki";
public final static String ATTR_NAME_COMMENT = PREFIX + ":" + "comment";
public final static String ATTR_NAME_CONTENTTYPE = PREFIX + ":" + "contentType";
public final static String ATTR_NAME_STATUS = PREFIX + ":" + "status";
public final static String ATTR_NAME_CREATOR = PREFIX + ":" + "creator";
public final static String ATTR_NAME_SHARED = PREFIX + ":" + "shared";
public final static String ATTR_NAME_TYPE = PREFIX + ":" + "type";
public final static String ATTR_NAME_FILENAME = PREFIX + ":" + "filename";
public final static String ATTR_NAME_SIZE = PREFIX + ":" + "size";
public final static String ATTR_NAME_DATE = PREFIX + ":" + "date";
private String filename;
private String contentType;
private String nodeUuid;
private String comment;
private boolean shared;
//it is useful for lucence search, but no idea how to extract this value from MS WORD, EXCEL or PDF. Left it just for future use.
private String encoding;
private long size;
// version.getName()
private String version;
//page or user 's attachment
private transient String type;
//for browser display index
private String index;
//pageUuid or username etc.
private String identifier;
//is zip format for bulk uploading?
private boolean bulkZip;
//some transient fields which won't pass back to
private transient InputStream file;
//current, auto draft, manual draft
private transient int status;
//username, it won't display on page. userFullname is good.
private String createor;
private long date;
//********************************************************************
//for display use
private String userFullname;
private String errorCode;
//these used by upload.jsp javascript templ for display purpose
public String displayDate;
public String url;
public String deleteUrl;
private String error;
//********************************************************************
// Function methods
//********************************************************************
public String toString(){
return "Filename:" + filename + ";nodeUuid:" + nodeUuid + ";identifier"+ identifier;
}
public void closeStream() {
if(file != null){
try {
file.close();
} catch (Exception e) {
}
}
}
public static void copyNodeToPersist(FileNode my, CrFileNode filenode) {
filenode.setNodeType(my.getType());
filenode.setIdentifierUuid(my.getIdentifier());
filenode.setNodeUuid(my.getNodeUuid());
filenode.setFilename(my.getFilename());
filenode.setComment(my.getComment());
// filenode.setVersion(my.getVersion());
//does not include spaceUname
filenode.setEncoding(my.getEncoding());
filenode.setContentType(my.getContentType());
filenode.setShared(my.isShared());
filenode.setSize(my.getSize());
filenode.setStatus(my.getStatus());
filenode.setCreator(my.getCreateor());
filenode.setModifiedDate(new Date());
}
public static FileNode copyPersistToNode(CrFileNode fileNode) {
//does not include spaceUname
FileNode my = new FileNode();
my.setType(fileNode.getNodeType());
my.setIdentifier(fileNode.getIdentifierUuid());
my.setNodeUuid(fileNode.getNodeUuid());
my.setFilename(fileNode.getFilename());
my.setComment(fileNode.getComment());
my.setEncoding(fileNode.getEncoding());
my.setContentType(fileNode.getContentType());
my.setStatus(fileNode.getStatus());
my.setCreateor(fileNode.getCreator());
my.setShared(fileNode.isShared());
my.setDate(fileNode.getModifiedDate().getTime());
my.setSize(fileNode.getSize());
my.setVersion(Integer.valueOf(fileNode.getVersion()).toString());
return my;
}
/**
* Warning: this method will modify FileNode in parameter list directly.
*
* Construct display information for upload.jsp javascript display purpose.
* @param files
* @param spaceUname
* @param messageService
* @param userReadingService
* @return
* @throws UnsupportedEncodingException
*/
public static String toAttachmentsJson(List<FileNode> files, String spaceUname, User viewer, MessageService messageService, UserReadingService userReadingService) throws UnsupportedEncodingException {
// convert fileNode to json that for JS template in upload.jsp.
Gson gson = new Gson();
for (FileNode fileNode : files) {
if(StringUtils.isEmpty(fileNode.getFilename())){
//This could be an error node, skip further message processing/
continue;
}
fileNode.displayDate = DateUtil.toDisplayDate(viewer, new Date(fileNode.getDate()),messageService);
fileNode.url = WebUtil.getPageRepoFileUrl(WebUtil.getHostAppURL(),spaceUname, fileNode.getFilename(), fileNode.getNodeUuid(), true);
fileNode.deleteUrl = WebUtil.getHostAppURL() + "pages/pages!removeAttachment.do?s=" + URLEncoder.encode(spaceUname, Constants.UTF8)
+ "&u=" + URLEncoder.encode(fileNode.getIdentifier(), Constants.UTF8)
- + "&nodeUuid=" + URLEncoder.encode(fileNode.getNodeUuid(), Constants.UTF8);
+ + "&nodeUuid=" + URLEncoder.encode(fileNode.getNodeUuid(), Constants.UTF8)
+ + "&_=" + System.currentTimeMillis();
//pass back user fullname
User user = userReadingService.getUserByName(fileNode.createor);
fileNode.setUserFullname(user.getFullname());
}
return gson.toJson(files);
}
// /**
// * @param child
// * @param withHistory
// * @throws RepositoryException
// */
// public static void copy(Node fileNode, List<FileNode> filelist, boolean withHistory, boolean withResource) throws RepositoryException {
//
// //node and all history have same uuid, so get it here.
// String uuid = fileNode.getUUID();
// if(!withHistory){
// //just copy baseverion info
// filelist.add(copy(uuid,fileNode.getBaseVersion(),fileNode,withResource));
// return;
// }
//
// VersionHistory history = fileNode.getVersionHistory();
// VersionIterator verIter = history.getAllVersions();
// //skip jcr:rootVersion
// verIter.skip(1);
// while(verIter.hasNext()){
// Version ver = (Version) verIter.next();
// NodeIterator nodeIter = ver.getNodes();
// while(nodeIter.hasNext()){
// Node child = (Node) nodeIter.next();
// filelist.add(copy(uuid,ver, child,withResource));
// }
// }
// }
//
// private static FileNode copy(String uuid, Version ver, Node node, boolean withResource) throws RepositoryException {
// FileNode my = new FileNode();
// my.nodeUuid = uuid;
// my.filename = node.getProperty(ATTR_NAME_FILENAME).getString();
// my.comment = node.getProperty(ATTR_NAME_COMMENT).getString();
// my.contentType = node.getProperty(ATTR_NAME_CONTENTTYPE).getString();
// my.status = (int) node.getProperty(ATTR_NAME_STATUS).getLong();
// my.createor = node.getProperty(ATTR_NAME_CREATOR).getString();
// my.shared = node.getProperty(ATTR_NAME_SHARED).getBoolean();
// my.type = node.getProperty(ATTR_NAME_TYPE).getString();
// my.date= node.getProperty(ATTR_NAME_DATE).getDate().getTime();
// my.size = node.getProperty(ATTR_NAME_SIZE).getLong();
// my.version = ver.getName();
//
// //copy geniuswiki:filenode->nt:resource node as well
// if(withResource){
// Node resNode = node.getNode("jcr:content");
// Property data = resNode.getProperty("jcr:data");
// my.file = data.getStream();
// }
// return my;
// }
//********************************************************************
// Set / Get
//********************************************************************
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public InputStream getFile() {
return file;
}
public void setFile(InputStream file) {
this.file = file;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public String getNodeUuid() {
return nodeUuid;
}
public void setNodeUuid(String nodeUuid) {
this.nodeUuid = nodeUuid;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCreateor() {
return createor;
}
public void setCreateor(String createor) {
this.createor = createor;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getUserFullname() {
return userFullname;
}
public void setUserFullname(String userFullname) {
this.userFullname = userFullname;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public boolean isBulkZip() {
return bulkZip;
}
public void setBulkZip(boolean bulkZip) {
this.bulkZip = bulkZip;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| true | true | public static String toAttachmentsJson(List<FileNode> files, String spaceUname, User viewer, MessageService messageService, UserReadingService userReadingService) throws UnsupportedEncodingException {
// convert fileNode to json that for JS template in upload.jsp.
Gson gson = new Gson();
for (FileNode fileNode : files) {
if(StringUtils.isEmpty(fileNode.getFilename())){
//This could be an error node, skip further message processing/
continue;
}
fileNode.displayDate = DateUtil.toDisplayDate(viewer, new Date(fileNode.getDate()),messageService);
fileNode.url = WebUtil.getPageRepoFileUrl(WebUtil.getHostAppURL(),spaceUname, fileNode.getFilename(), fileNode.getNodeUuid(), true);
fileNode.deleteUrl = WebUtil.getHostAppURL() + "pages/pages!removeAttachment.do?s=" + URLEncoder.encode(spaceUname, Constants.UTF8)
+ "&u=" + URLEncoder.encode(fileNode.getIdentifier(), Constants.UTF8)
+ "&nodeUuid=" + URLEncoder.encode(fileNode.getNodeUuid(), Constants.UTF8);
//pass back user fullname
User user = userReadingService.getUserByName(fileNode.createor);
fileNode.setUserFullname(user.getFullname());
}
return gson.toJson(files);
}
| public static String toAttachmentsJson(List<FileNode> files, String spaceUname, User viewer, MessageService messageService, UserReadingService userReadingService) throws UnsupportedEncodingException {
// convert fileNode to json that for JS template in upload.jsp.
Gson gson = new Gson();
for (FileNode fileNode : files) {
if(StringUtils.isEmpty(fileNode.getFilename())){
//This could be an error node, skip further message processing/
continue;
}
fileNode.displayDate = DateUtil.toDisplayDate(viewer, new Date(fileNode.getDate()),messageService);
fileNode.url = WebUtil.getPageRepoFileUrl(WebUtil.getHostAppURL(),spaceUname, fileNode.getFilename(), fileNode.getNodeUuid(), true);
fileNode.deleteUrl = WebUtil.getHostAppURL() + "pages/pages!removeAttachment.do?s=" + URLEncoder.encode(spaceUname, Constants.UTF8)
+ "&u=" + URLEncoder.encode(fileNode.getIdentifier(), Constants.UTF8)
+ "&nodeUuid=" + URLEncoder.encode(fileNode.getNodeUuid(), Constants.UTF8)
+ "&_=" + System.currentTimeMillis();
//pass back user fullname
User user = userReadingService.getUserByName(fileNode.createor);
fileNode.setUserFullname(user.getFullname());
}
return gson.toJson(files);
}
|
diff --git a/jenkow-plugin/src/main/java/com/cisco/step/jenkins/plugins/jenkow/JenkowEngine.java b/jenkow-plugin/src/main/java/com/cisco/step/jenkins/plugins/jenkow/JenkowEngine.java
index def6ff1..8fa84d0 100644
--- a/jenkow-plugin/src/main/java/com/cisco/step/jenkins/plugins/jenkow/JenkowEngine.java
+++ b/jenkow-plugin/src/main/java/com/cisco/step/jenkins/plugins/jenkow/JenkowEngine.java
@@ -1,109 +1,110 @@
/*
* The MIT License
*
* Copyright (c) 2012, Cisco Systems, Inc., Max Spring
*
* 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.cisco.step.jenkins.plugins.jenkow;
import com.cisco.step.jenkins.plugins.jenkow.identity.IdentityServiceImpl;
import hudson.tasks.Mailer;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.impl.bpmn.parser.BpmnParseListener;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.jenkinsci.plugins.database.Database;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class JenkowEngine {
private static final Logger LOG = Logger.getLogger(JenkowEngine.class.getName());
private static ProcessEngine engine;
public static ProcessEngine getEngine(){
if (engine == null){
Database ec = JenkowBuilder.descriptor().getDatabase();
LOG.info("engineConfig="+ec);
ProcessEngineConfiguration cfg;
// context for *all* processes. available in exppressions and scripts in the process.
Map<Object,Object> ctxBeans = new HashMap<Object,Object>();
ctxBeans.put("log",LOG);
if (ec instanceof H2DemoDatabase) {
cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
// we will be sharing this database with Activiti Explorer, so don't force re-creation of the whole DB
// and honor what's already there
cfg.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
} else {
cfg = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
Mailer.DescriptorImpl md = Mailer.descriptor();
System.out.println("mailer config");
System.out.println("md.getSmtpServer() -> "+md.getSmtpServer());
System.out.println("md.getDefaultSuffix() -> "+md.getDefaultSuffix());
System.out.println("md.getReplyToAddress() -> "+md.getReplyToAddress());
System.out.println("md.getSmtpPort() -> "+md.getSmtpPort());
// set database config
try {
cfg.setDataSource(ec.getDataSource());
} catch (SQLException e) {
throw new Error(e); // TODO: what's the error handling strategy in this method?
}
// set other engine config
cfg.setDatabaseSchemaUpdate("true");
cfg.setHistory("full");
}
cfg.setJobExecutorActivate(true);
ClassLoader peCL = JenkowEngine.class.getClassLoader();
Thread.currentThread().setContextClassLoader(peCL);
// set common cfg here.
ProcessEngineConfigurationImpl peCfg = (ProcessEngineConfigurationImpl)cfg;
peCfg.setIdentityService(new IdentityServiceImpl());
peCfg.setBeans(ctxBeans);
List<BpmnParseListener> preParseListeners = peCfg.getPreParseListeners();
if (preParseListeners == null){
preParseListeners = new ArrayList<BpmnParseListener>();
peCfg.setPreParseListeners(preParseListeners);
}
preParseListeners.add(new JenkowBpmnParseListener());
cfg.setClassLoader(peCL);
// build engine
engine = cfg.buildProcessEngine();
+ LOG.info("created Activiti workflow engine v"+engine.VERSION);
JenkowPlugin.getInstance().repo.deployAllToEngine();
}
return engine;
}
static void closeEngine(){
LOG.info("closing engine");
if (engine != null) engine.close();
engine = null;
}
}
| true | true | public static ProcessEngine getEngine(){
if (engine == null){
Database ec = JenkowBuilder.descriptor().getDatabase();
LOG.info("engineConfig="+ec);
ProcessEngineConfiguration cfg;
// context for *all* processes. available in exppressions and scripts in the process.
Map<Object,Object> ctxBeans = new HashMap<Object,Object>();
ctxBeans.put("log",LOG);
if (ec instanceof H2DemoDatabase) {
cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
// we will be sharing this database with Activiti Explorer, so don't force re-creation of the whole DB
// and honor what's already there
cfg.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
} else {
cfg = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
Mailer.DescriptorImpl md = Mailer.descriptor();
System.out.println("mailer config");
System.out.println("md.getSmtpServer() -> "+md.getSmtpServer());
System.out.println("md.getDefaultSuffix() -> "+md.getDefaultSuffix());
System.out.println("md.getReplyToAddress() -> "+md.getReplyToAddress());
System.out.println("md.getSmtpPort() -> "+md.getSmtpPort());
// set database config
try {
cfg.setDataSource(ec.getDataSource());
} catch (SQLException e) {
throw new Error(e); // TODO: what's the error handling strategy in this method?
}
// set other engine config
cfg.setDatabaseSchemaUpdate("true");
cfg.setHistory("full");
}
cfg.setJobExecutorActivate(true);
ClassLoader peCL = JenkowEngine.class.getClassLoader();
Thread.currentThread().setContextClassLoader(peCL);
// set common cfg here.
ProcessEngineConfigurationImpl peCfg = (ProcessEngineConfigurationImpl)cfg;
peCfg.setIdentityService(new IdentityServiceImpl());
peCfg.setBeans(ctxBeans);
List<BpmnParseListener> preParseListeners = peCfg.getPreParseListeners();
if (preParseListeners == null){
preParseListeners = new ArrayList<BpmnParseListener>();
peCfg.setPreParseListeners(preParseListeners);
}
preParseListeners.add(new JenkowBpmnParseListener());
cfg.setClassLoader(peCL);
// build engine
engine = cfg.buildProcessEngine();
JenkowPlugin.getInstance().repo.deployAllToEngine();
}
return engine;
}
| public static ProcessEngine getEngine(){
if (engine == null){
Database ec = JenkowBuilder.descriptor().getDatabase();
LOG.info("engineConfig="+ec);
ProcessEngineConfiguration cfg;
// context for *all* processes. available in exppressions and scripts in the process.
Map<Object,Object> ctxBeans = new HashMap<Object,Object>();
ctxBeans.put("log",LOG);
if (ec instanceof H2DemoDatabase) {
cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
// we will be sharing this database with Activiti Explorer, so don't force re-creation of the whole DB
// and honor what's already there
cfg.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
} else {
cfg = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
Mailer.DescriptorImpl md = Mailer.descriptor();
System.out.println("mailer config");
System.out.println("md.getSmtpServer() -> "+md.getSmtpServer());
System.out.println("md.getDefaultSuffix() -> "+md.getDefaultSuffix());
System.out.println("md.getReplyToAddress() -> "+md.getReplyToAddress());
System.out.println("md.getSmtpPort() -> "+md.getSmtpPort());
// set database config
try {
cfg.setDataSource(ec.getDataSource());
} catch (SQLException e) {
throw new Error(e); // TODO: what's the error handling strategy in this method?
}
// set other engine config
cfg.setDatabaseSchemaUpdate("true");
cfg.setHistory("full");
}
cfg.setJobExecutorActivate(true);
ClassLoader peCL = JenkowEngine.class.getClassLoader();
Thread.currentThread().setContextClassLoader(peCL);
// set common cfg here.
ProcessEngineConfigurationImpl peCfg = (ProcessEngineConfigurationImpl)cfg;
peCfg.setIdentityService(new IdentityServiceImpl());
peCfg.setBeans(ctxBeans);
List<BpmnParseListener> preParseListeners = peCfg.getPreParseListeners();
if (preParseListeners == null){
preParseListeners = new ArrayList<BpmnParseListener>();
peCfg.setPreParseListeners(preParseListeners);
}
preParseListeners.add(new JenkowBpmnParseListener());
cfg.setClassLoader(peCL);
// build engine
engine = cfg.buildProcessEngine();
LOG.info("created Activiti workflow engine v"+engine.VERSION);
JenkowPlugin.getInstance().repo.deployAllToEngine();
}
return engine;
}
|
diff --git a/orcid-web/src/main/java/org/orcid/frontend/web/controllers/ManageProfileController.java b/orcid-web/src/main/java/org/orcid/frontend/web/controllers/ManageProfileController.java
index 45e5b2b2cc..6300ab30d1 100644
--- a/orcid-web/src/main/java/org/orcid/frontend/web/controllers/ManageProfileController.java
+++ b/orcid-web/src/main/java/org/orcid/frontend/web/controllers/ManageProfileController.java
@@ -1,859 +1,859 @@
/**
* =============================================================================
*
* ORCID (R) Open Source
* http://orcid.org
*
* Copyright (c) 2012-2013 ORCID, Inc.
* Licensed under an MIT-Style License (MIT)
* http://orcid.org/open-source-license
*
* This copyright and license information (including a link to the full license)
* shall be included in its entirety in all copies or substantial portion of
* the software.
*
* =============================================================================
*/
package org.orcid.frontend.web.controllers;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.orcid.core.manager.EncryptionManager;
import org.orcid.core.manager.NotificationManager;
import org.orcid.core.manager.OrcidSearchManager;
import org.orcid.core.manager.OtherNameManager;
import org.orcid.core.manager.ProfileEntityManager;
import org.orcid.core.manager.ProfileKeywordManager;
import org.orcid.core.manager.ResearcherUrlManager;
import org.orcid.core.oauth.OrcidProfileUserDetails;
import org.orcid.core.utils.SolrFieldWeight;
import org.orcid.core.utils.SolrQueryBuilder;
import org.orcid.frontend.web.forms.AddDelegateForm;
import org.orcid.frontend.web.forms.ChangePasswordForm;
import org.orcid.frontend.web.forms.ChangePersonalInfoForm;
import org.orcid.frontend.web.forms.ChangeSecurityQuestionForm;
import org.orcid.frontend.web.forms.ManagePasswordOptionsForm;
import org.orcid.frontend.web.forms.PreferencesForm;
import org.orcid.frontend.web.forms.SearchForDelegatesForm;
import org.orcid.jaxb.model.message.Delegation;
import org.orcid.jaxb.model.message.DelegationDetails;
import org.orcid.jaxb.model.message.Email;
import org.orcid.jaxb.model.message.EncryptedSecurityAnswer;
import org.orcid.jaxb.model.message.GivenPermissionBy;
import org.orcid.jaxb.model.message.GivenPermissionTo;
import org.orcid.jaxb.model.message.Keywords;
import org.orcid.jaxb.model.message.OrcidMessage;
import org.orcid.jaxb.model.message.OrcidProfile;
import org.orcid.jaxb.model.message.OrcidSearchResults;
import org.orcid.jaxb.model.message.OrcidType;
import org.orcid.jaxb.model.message.OtherNames;
import org.orcid.jaxb.model.message.Preferences;
import org.orcid.jaxb.model.message.ResearcherUrl;
import org.orcid.jaxb.model.message.ResearcherUrls;
import org.orcid.jaxb.model.message.ScopePathType;
import org.orcid.jaxb.model.message.SecurityDetails;
import org.orcid.jaxb.model.message.SecurityQuestionId;
import org.orcid.jaxb.model.message.Url;
import org.orcid.jaxb.model.message.UrlName;
import org.orcid.jaxb.model.message.Visibility;
import org.orcid.jaxb.model.message.WorkExternalIdentifierType;
import org.orcid.password.constants.OrcidPasswordConstants;
import org.orcid.persistence.jpa.entities.ResearcherUrlEntity;
import org.orcid.pojo.ChangePassword;
import org.orcid.pojo.SecurityQuestion;
import org.orcid.pojo.ajaxForm.Emails;
import org.orcid.pojo.ajaxForm.Errors;
import org.orcid.utils.OrcidWebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import schema.constants.SolrConstants;
/**
* Copyright 2011-2012 ORCID
*
* @author Declan Newman (declan) Date: 22/02/2012
*/
@Controller("manageProfileController")
@RequestMapping(value = { "/account", "/manage" })
public class ManageProfileController extends BaseWorkspaceController {
private static final Logger LOGGER = LoggerFactory.getLogger(ManageProfileController.class);
/*
* session attribute that is used to see if we should check and notify the
* user if their primary email ins't verified.
*/
public static String CHECK_EMAIL_VALIDATED = "CHECK_EMAIL_VALIDATED";
@Resource
private OrcidSearchManager orcidSearchManager;
@Resource
private EncryptionManager encryptionManager;
@Resource
private NotificationManager notificationManager;
@Resource
private ResearcherUrlManager researcherUrlManager;
@Resource
private ProfileKeywordManager profileKeywordManager;
@Resource
private OtherNameManager otherNameManager;
@Resource
private ProfileEntityManager profileEntityManager;
public EncryptionManager getEncryptionManager() {
return encryptionManager;
}
public void setEncryptionManager(EncryptionManager encryptionManager) {
this.encryptionManager = encryptionManager;
}
public void setNotificationManager(NotificationManager notificationManager) {
this.notificationManager = notificationManager;
}
public void setResearcherUrlManager(ResearcherUrlManager researcherUrlManager) {
this.researcherUrlManager = researcherUrlManager;
}
public void setProfileKeywordManager(ProfileKeywordManager profileKeywordManager) {
this.profileKeywordManager = profileKeywordManager;
}
public void setOtherNameManager(OtherNameManager otherNameManager) {
this.otherNameManager = otherNameManager;
}
@ModelAttribute("visibilities")
public Map<String, String> retrieveVisibilitiesAsMap() {
Map<String, String> visibilities = new LinkedHashMap<String, String>();
visibilities.put(Visibility.PUBLIC.value(), "Public");
visibilities.put(Visibility.LIMITED.value(), "Limited");
visibilities.put(Visibility.PRIVATE.value(), "Private");
return visibilities;
}
@ModelAttribute("externalIdentifierRefData")
public Map<String, String> retrieveExternalIdentifierRefData() {
Map<String, String> types = new HashMap<String, String>();
for (WorkExternalIdentifierType type : WorkExternalIdentifierType.values()) {
types.put(type.value(), buildInternationalizationKey(WorkExternalIdentifierType.class, type.value()));
}
return types;
}
@RequestMapping
public ModelAndView manageProfile(@RequestParam(value = "activeTab", required = false) String activeTab) {
String tab = activeTab == null ? "profile-tab" : activeTab;
ModelAndView mav = rebuildManageView(tab);
return mav;
}
@RequestMapping(value = "/preferences", method = RequestMethod.POST)
public ModelAndView updatePreferences(@ModelAttribute("preferencesForm") PreferencesForm preferencesForm, RedirectAttributes redirectAttributes) {
ModelAndView mav = new ModelAndView("redirect:/account?activeTab=options-tab");
LOGGER.debug("Got preferences: {}", preferencesForm);
orcidProfileManager.updatePreferences(preferencesForm.getOrcidProfile());
redirectAttributes.addFlashAttribute("optionsSaved", true);
return mav;
}
@RequestMapping(value = "/search-for-delegates", method = RequestMethod.GET)
public ModelAndView viewSearchForDelegates() {
ModelAndView mav = new ModelAndView("search_for_delegates");
return mav;
}
@RequestMapping(value = "/search-for-delegates", method = RequestMethod.POST)
public ModelAndView searchForDelegates(@RequestParam("searchTerms") String searchTerms) {
SolrQueryBuilder queryBuilder = new SolrQueryBuilder();
List<SolrFieldWeight> fields = new ArrayList<SolrFieldWeight>();
fields.add(new SolrFieldWeight(SolrConstants.GIVEN_NAMES, 2.0f));
fields.add(new SolrFieldWeight(SolrConstants.FAMILY_NAME, 3.0f));
fields.add(new SolrFieldWeight(SolrConstants.CREDIT_NAME, 3.0f));
fields.add(new SolrFieldWeight(SolrConstants.EMAIL_ADDRESS, 4.0f));
fields.add(new SolrFieldWeight(SolrConstants.TEXT, 0.5f));
fields.add(new SolrFieldWeight(SolrConstants.AFFILIATE_PRIMARY_INSTITUTION_NAMES, 1.0f));
queryBuilder.appendEDisMaxQuery(fields);
queryBuilder.appendValue(searchTerms);
OrcidProfile orcidProfile = getEffectiveProfile();
List<String> orcidsToExclude = new ArrayList<String>();
// Exclude myself
orcidsToExclude.add(orcidProfile.getOrcid().getValue());
// Exclude profiles I've already delegated to
Delegation delegation = orcidProfile.getOrcidBio().getDelegation();
if (delegation != null) {
GivenPermissionTo givenPermissionTo = delegation.getGivenPermissionTo();
if (givenPermissionTo != null) {
for (DelegationDetails delegationDetails : givenPermissionTo.getDelegationDetails()) {
orcidsToExclude.add(delegationDetails.getDelegateSummary().getOrcid().getValue());
}
}
}
queryBuilder.appendNOTCondition(SolrConstants.ORCID, orcidsToExclude);
// XXX Use T1 API
OrcidMessage orcidMessage = orcidSearchManager.findOrcidsByQuery(queryBuilder.retrieveQuery());
OrcidSearchResults searchResults = orcidMessage.getOrcidSearchResults();
SearchForDelegatesForm searchForDelegatesForm = new SearchForDelegatesForm(searchResults);
ModelAndView mav = new ModelAndView("search_for_delegates_results");
mav.addObject(searchForDelegatesForm);
return mav;
}
@RequestMapping(value = "/confirm-delegate", method = RequestMethod.POST)
public ModelAndView confirmDelegate(@ModelAttribute("delegateOrcid") String delegateOrcid) {
OrcidProfile delegateProfile = orcidProfileManager.retrieveOrcidProfile(delegateOrcid);
ModelAndView mav = new ModelAndView("confirm_delegate");
mav.addObject("delegateProfile", delegateProfile);
return mav;
}
@RequestMapping(value = "/add-delegate")
public ModelAndView addDelegate(@ModelAttribute AddDelegateForm addDelegateForm) {
OrcidProfile profile = addDelegateForm.getOrcidProfile(getCurrentUserOrcid());
orcidProfileManager.addDelegates(profile);
ModelAndView mav = new ModelAndView("redirect:/account?activeTab=delegation-tab");
return mav;
}
@RequestMapping(value = "/revoke-delegate", method = RequestMethod.POST)
public ModelAndView revokeDelegate(@RequestParam String receiverOrcid) {
String giverOrcid = getCurrentUserOrcid();
orcidProfileManager.revokeDelegate(giverOrcid, receiverOrcid);
ModelAndView mav = new ModelAndView("redirect:/account?activeTab=delegation-tab");
return mav;
}
@RequestMapping(value = "/revoke-delegate-from-summary-view", method = RequestMethod.GET)
public ModelAndView revokeDelegateFromSummaryView(@RequestParam("orcid") String receiverOrcid) {
String giverOrcid = getCurrentUserOrcid();
orcidProfileManager.revokeDelegate(giverOrcid, receiverOrcid);
ModelAndView mav = new ModelAndView("redirect:/account/view-account-settings");
return mav;
}
@RequestMapping(value = "/revoke-application")
public ModelAndView revokeApplication(@RequestParam("applicationOrcid") String applicationOrcid,
@RequestParam(value = "scopePaths", required = false, defaultValue = "") String[] scopePaths) {
String userOrcid = getCurrentUserOrcid();
orcidProfileManager.revokeApplication(userOrcid, applicationOrcid, ScopePathType.getScopesFromStrings(Arrays.asList(scopePaths)));
ModelAndView mav = new ModelAndView("redirect:/account?activeTab=application-tab");
return mav;
}
@RequestMapping(value = "/revoke-application-from-summary-view", method = RequestMethod.GET)
public ModelAndView revokeApplicationFromSummaryView(@RequestParam("applicationOrcid") String applicationOrcid, @RequestParam("scopePaths") String[] scopePaths) {
String userOrcid = getCurrentUserOrcid();
orcidProfileManager.revokeApplication(userOrcid, applicationOrcid, ScopePathType.getScopesFromStrings(Arrays.asList(scopePaths)));
ModelAndView mav = new ModelAndView("redirect:/account/view-account-settings");
return mav;
}
@RequestMapping(value = "/switch-user", method = RequestMethod.POST)
public ModelAndView switchUser(HttpServletRequest request, @RequestParam("giverOrcid") String giverOrcid) {
OrcidProfileUserDetails userDetails = getCurrentUser();
// Check permissions!
if (isInDelegationMode()) {
// If already in delegation mode, check that is switching back to
// current user
if (!getRealUserOrcid().equals(giverOrcid)) {
throw new AccessDeniedException("You are not allowed to switch back to that user");
}
} else {
// If not yet in delegation mode, then check that the real user has
// permission to become the giver
if (!hasDelegatePermission(userDetails, giverOrcid)) {
throw new AccessDeniedException("You are not allowed to switch to that user");
}
}
getCurrentUser().switchDelegationMode(giverOrcid);
request.getSession().removeAttribute(WORKS_RESULTS_ATTRIBUTE);
ModelAndView mav = new ModelAndView("redirect:/my-orcid");
return mav;
}
@RequestMapping(value = "/admin-switch-user", method = RequestMethod.GET)
public ModelAndView adminSwitchUser(HttpServletRequest request, @RequestParam("orcid") String targetOrcid) {
// Check permissions!
if (!OrcidType.ADMIN.equals(getRealProfile().getType())) {
throw new AccessDeniedException("You are not allowed to switch to that user");
}
getCurrentUser().switchDelegationMode(targetOrcid);
request.getSession().removeAttribute(WORKS_RESULTS_ATTRIBUTE);
ModelAndView mav = new ModelAndView("redirect:/my-orcid");
return mav;
}
private boolean hasDelegatePermission(OrcidProfileUserDetails userDetails, String giverOrcid) {
Delegation delegation = getRealProfile().getOrcidBio().getDelegation();
if (delegation != null) {
GivenPermissionBy givenPermissionBy = delegation.getGivenPermissionBy();
if (givenPermissionBy != null) {
for (DelegationDetails delegationDetails : givenPermissionBy.getDelegationDetails()) {
if (delegationDetails.getDelegateSummary().getOrcid().getValue().equals(giverOrcid)) {
return true;
}
}
}
}
return false;
}
protected ModelAndView rebuildManageView(String activeTab) {
ModelAndView mav = new ModelAndView("manage");
mav.addObject("showPrivacy", true);
OrcidProfile profile = getEffectiveProfile();
mav.addObject("managePasswordOptionsForm", populateManagePasswordFormFromUserInfo());
mav.addObject("preferencesForm", new PreferencesForm(profile));
mav.addObject("profile", profile);
mav.addObject("activeTab", activeTab);
mav.addObject("securityQuestions", getSecurityQuestions());
return mav;
}
private ManagePasswordOptionsForm populateManagePasswordFormFromUserInfo() {
OrcidProfile profile = getEffectiveProfile();
// TODO - placeholder just to test the retrieve etc..replace with only
// fields that we will populate
// password fields are never populated
OrcidProfile unecryptedProfile = orcidProfileManager.retrieveOrcidProfile(profile.getOrcid().getValue());
ManagePasswordOptionsForm managePasswordOptionsForm = new ManagePasswordOptionsForm();
managePasswordOptionsForm.setVerificationNumber(unecryptedProfile.getVerificationCode());
managePasswordOptionsForm.setSecurityQuestionAnswer(unecryptedProfile.getSecurityQuestionAnswer());
Integer securityQuestionId = null;
SecurityDetails securityDetails = unecryptedProfile.getOrcidInternal().getSecurityDetails();
// TODO - confirm that security details aren't null and that we can
// change schema to be an int for security
// questions field
if (securityDetails != null) {
securityQuestionId = securityDetails.getSecurityQuestionId() != null ? new Integer((int) securityDetails.getSecurityQuestionId().getValue()) : null;
}
managePasswordOptionsForm.setSecurityQuestionId(securityQuestionId);
return managePasswordOptionsForm;
}
@ModelAttribute("changeNotificationsMap")
public Map<String, String> getChangeNotificationsMap() {
Map<String, String> changeNotificationsMap = new HashMap<String, String>();
changeNotificationsMap.put("sendMe", "");
return changeNotificationsMap;
}
@ModelAttribute("orcidNewsMap")
public Map<String, String> getOrcidNewsMap() {
Map<String, String> orcidNewsMap = new HashMap<String, String>();
orcidNewsMap.put("sendMe", "");
return orcidNewsMap;
}
@ModelAttribute("colleagueConfirmedRegistrationMap")
public Map<String, String> getColleagueConfirmedRegistrationMap() {
Map<String, String> otherNewsMap = new HashMap<String, String>();
otherNewsMap.put("sendMe", "");
return otherNewsMap;
}
@ModelAttribute("securityQuestions")
public Map<String, String> getSecurityQuestions() {
Map<String, String> securityQuestions = securityQuestionManager.retrieveSecurityQuestionsAsInternationalizedMap();
Map<String, String> securityQuestionsWithMessages = new LinkedHashMap<String, String>();
for (String key : securityQuestions.keySet()) {
securityQuestionsWithMessages.put(key, getMessage(securityQuestions.get(key)));
}
return securityQuestionsWithMessages;
}
@RequestMapping(value = "/view-account-settings", method = RequestMethod.GET)
public String viewAccountSettings() {
// Defunct page, redirect to main account page in case of bookmarks.
return "redirect:/account";
}
@RequestMapping(value = { "/security-question", "/change-security-question" }, method = RequestMethod.GET)
public ModelAndView viewChangeSecurityQuestion() {
return populateChangeSecurityDetailsViewFromUserProfile(new ChangeSecurityQuestionForm());
}
@RequestMapping(value = { "/security-question", "/change-security-question" }, method = RequestMethod.POST)
public ModelAndView updateWithChangedSecurityQuestion(@ModelAttribute("changeSecurityQuestionForm") @Valid ChangeSecurityQuestionForm changeSecurityQuestionForm,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
ModelAndView changeSecurityDetailsView = new ModelAndView("change_security_question");
changeSecurityDetailsView.addAllObjects(bindingResult.getModel());
changeSecurityDetailsView.addObject(changeSecurityQuestionForm);
return changeSecurityDetailsView;
}
OrcidProfile profile = getEffectiveProfile();
profile.setSecurityQuestionAnswer(changeSecurityQuestionForm.getSecurityQuestionAnswer());
profile.getOrcidInternal().getSecurityDetails().setSecurityQuestionId(new SecurityQuestionId(changeSecurityQuestionForm.getSecurityQuestionId()));
orcidProfileManager.updateSecurityQuestionInformation(profile);
ModelAndView changeSecurityDetailsView = populateChangeSecurityDetailsViewFromUserProfile(changeSecurityQuestionForm);
changeSecurityDetailsView.addObject("securityQuestionSaved", true);
return changeSecurityDetailsView;
}
@RequestMapping(value = "/security-question.json", method = RequestMethod.GET)
public @ResponseBody
SecurityQuestion getSecurityQuestionJson(HttpServletRequest request) {
OrcidProfile profile = getEffectiveProfile();
SecurityDetails sd = profile.getOrcidInternal().getSecurityDetails();
SecurityQuestionId securityQuestionId = sd.getSecurityQuestionId();
EncryptedSecurityAnswer encryptedSecurityAnswer = sd.getEncryptedSecurityAnswer();
if (securityQuestionId == null) {
sd.getSecurityQuestionId();
securityQuestionId = new SecurityQuestionId();
}
SecurityQuestion securityQuestion = new SecurityQuestion();
securityQuestion.setSecurityQuestionId(securityQuestionId.getValue());
if (encryptedSecurityAnswer != null) {
securityQuestion.setSecurityAnswer(encryptionManager.decryptForInternalUse(encryptedSecurityAnswer.getContent()));
}
return securityQuestion;
}
@RequestMapping(value = "/security-question.json", method = RequestMethod.POST)
public @ResponseBody
SecurityQuestion setSecurityQuestionJson(HttpServletRequest request, @RequestBody SecurityQuestion securityQuestion) {
List<String> errors = new ArrayList<String>();
if (securityQuestion.getSecurityQuestionId() != 0 && (securityQuestion.getSecurityAnswer() == null || securityQuestion.getSecurityAnswer().trim() == ""))
errors.add(getMessage("manage.pleaseProvideAnAnswer"));
if (securityQuestion.getPassword() == null || !encryptionManager.hashMatches(securityQuestion.getPassword(), getEffectiveProfile().getPassword())) {
errors.add(getMessage("check_password_modal.incorrect_password"));
}
// If the security question is empty, clean the security answer field
if (securityQuestion.getSecurityQuestionId() == 0)
securityQuestion.setSecurityAnswer(new String());
if (errors.size() == 0) {
OrcidProfile profile = getEffectiveProfile();
if (profile.getOrcidInternal().getSecurityDetails().getSecurityQuestionId() == null)
profile.getOrcidInternal().getSecurityDetails().setSecurityQuestionId(new SecurityQuestionId());
profile.getOrcidInternal().getSecurityDetails().getSecurityQuestionId().setValue(securityQuestion.getSecurityQuestionId());
if (profile.getOrcidInternal().getSecurityDetails().getEncryptedSecurityAnswer() == null)
profile.getOrcidInternal().getSecurityDetails().setEncryptedSecurityAnswer(new EncryptedSecurityAnswer());
profile.setSecurityQuestionAnswer(securityQuestion.getSecurityAnswer());
orcidProfileManager.updateSecurityQuestionInformation(profile);
errors.add(getMessage("manage.securityQuestionUpdated"));
}
securityQuestion.setErrors(errors);
return securityQuestion;
}
@RequestMapping(value = "/preferences.json", method = RequestMethod.GET)
public @ResponseBody
Preferences getDefaultPreference(HttpServletRequest request) {
OrcidProfile profile = getEffectiveProfile();
profile.getOrcidInternal().getPreferences();
return profile.getOrcidInternal().getPreferences() != null ? profile.getOrcidInternal().getPreferences() : new Preferences();
}
@RequestMapping(value = "/preferences.json", method = RequestMethod.POST)
public @ResponseBody
Preferences setDefaultPreference(HttpServletRequest request, @RequestBody Preferences preferences) {
OrcidProfile profile = orcidProfileManager.retrieveOrcidProfile(getCurrentUserOrcid());
profile.getOrcidInternal().setPreferences(preferences);
OrcidProfile updatedProfile = orcidProfileManager.updateOrcidProfile(profile);
return updatedProfile.getOrcidInternal().getPreferences();
}
private ModelAndView populateChangeSecurityDetailsViewFromUserProfile(ChangeSecurityQuestionForm changeSecurityQuestionForm) {
ModelAndView changeSecurityDetailsView = new ModelAndView("change_security_question");
Integer securityQuestionId = null;
SecurityDetails securityDetails = getEffectiveProfile().getOrcidInternal().getSecurityDetails();
if (securityDetails != null) {
securityQuestionId = securityDetails.getSecurityQuestionId() != null ? new Integer((int) securityDetails.getSecurityQuestionId().getValue()) : null;
}
String encryptedSecurityAnswer = securityDetails != null && securityDetails.getEncryptedSecurityAnswer() != null ? securityDetails.getEncryptedSecurityAnswer()
.getContent() : null;
String securityAnswer = StringUtils.isNotBlank(encryptedSecurityAnswer) ? encryptionManager.decryptForInternalUse(encryptedSecurityAnswer) : "";
changeSecurityQuestionForm.setSecurityQuestionId(securityQuestionId);
changeSecurityQuestionForm.setSecurityQuestionAnswer(securityAnswer);
changeSecurityDetailsView.addObject("changeSecurityQuestionForm", changeSecurityQuestionForm);
return changeSecurityDetailsView;
}
@RequestMapping(value = { "/change-password.json" }, method = RequestMethod.GET)
public @ResponseBody
ChangePassword getChangedPasswordJson(HttpServletRequest request) {
ChangePassword p = new ChangePassword();
return p;
}
@RequestMapping(value = { "/change-password.json" }, method = RequestMethod.POST)
public @ResponseBody
ChangePassword changedPasswordJson(HttpServletRequest request, @RequestBody ChangePassword cp) {
List<String> errors = new ArrayList<String>();
if (cp.getPassword() == null || !cp.getPassword().matches(OrcidPasswordConstants.ORCID_PASSWORD_REGEX)) {
errors.add(getMessage("NotBlank.registrationForm.confirmedPassword"));
} else if (!cp.getPassword().equals(cp.getRetypedPassword())) {
errors.add(getMessage("FieldMatch.registrationForm"));
}
if (cp.getOldPassword() == null || !encryptionManager.hashMatches(cp.getOldPassword(), getEffectiveProfile().getPassword())) {
errors.add(getMessage("orcid.frontend.change.password.current_password_incorrect"));
}
if (errors.size() == 0) {
OrcidProfile profile = getEffectiveProfile();
profile.setPassword(cp.getPassword());
orcidProfileManager.updatePasswordInformation(profile);
cp = new ChangePassword();
errors.add(getMessage("orcid.frontend.change.password.change.successfully"));
}
cp.setErrors(errors);
return cp;
}
@RequestMapping(value = { "deactivate-orcid", "/view-deactivate-orcid-account" }, method = RequestMethod.GET)
public ModelAndView viewDeactivateOrcidAccount() {
ModelAndView deactivateOrcidView = new ModelAndView("deactivate_orcid");
return deactivateOrcidView;
}
@RequestMapping(value = "/confirm-deactivate-orcid", method = RequestMethod.GET)
public ModelAndView confirmDeactivateOrcidAccount(HttpServletRequest request) {
orcidProfileManager.deactivateOrcidProfile(getEffectiveProfile());
ModelAndView deactivateOrcidView = new ModelAndView("redirect:/signout#deactivated");
return deactivateOrcidView;
}
@RequestMapping(value = "/manage-bio-settings", method = RequestMethod.GET)
public ModelAndView viewEditBio(HttpServletRequest request) {
ModelAndView manageBioView = new ModelAndView("manage_bio_settings");
OrcidProfile profile = getEffectiveProfile();
ChangePersonalInfoForm changePersonalInfoForm = new ChangePersonalInfoForm(profile);
manageBioView.addObject("changePersonalInfoForm", changePersonalInfoForm);
return manageBioView;
}
@RequestMapping(value = "/verifyEmail.json", method = RequestMethod.GET)
public @ResponseBody
Errors verifyEmailJson(HttpServletRequest request, @RequestParam("email") String email) {
OrcidProfile currentProfile = getEffectiveProfile();
String primaryEmail = currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
if (primaryEmail.equals(email))
request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false);
URI baseUri = OrcidWebUtils.getServerUriWithContextPath(request);
notificationManager.sendVerificationEmail(currentProfile, baseUri, email);
return new Errors();
}
@RequestMapping(value = "/delayVerifyEmail.json", method = RequestMethod.GET)
public @ResponseBody
Errors delayVerifyEmailJson(HttpServletRequest request) {
request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false);
return new Errors();
}
@RequestMapping(value = "/send-deactivate-account.json", method = RequestMethod.GET)
public @ResponseBody
Email startDeactivateOrcidAccountJson(HttpServletRequest request) {
URI uri = OrcidWebUtils.getServerUriWithContextPath(request);
OrcidProfile currentProfile = getEffectiveProfile();
Email email = currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail();
notificationManager.sendOrcidDeactivateEmail(currentProfile, uri);
return email;
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/emails.json", method = RequestMethod.GET)
public @ResponseBody
org.orcid.pojo.ajaxForm.Emails getEmailsJson(HttpServletRequest request) throws NoSuchRequestHandlingMethodException {
OrcidProfile currentProfile = getEffectiveProfile();
Emails emails = new org.orcid.pojo.ajaxForm.Emails();
emails.setEmails((List<org.orcid.pojo.Email>) (Object) currentProfile.getOrcidBio().getContactDetails().getEmail());
return emails;
}
@RequestMapping(value = "/addEmail.json", method = RequestMethod.POST)
public @ResponseBody
org.orcid.pojo.Email addEmailsJson(HttpServletRequest request, @RequestBody org.orcid.pojo.AddEmail email) {
List<String> errors = new ArrayList<String>();
// Check password
if (email.getPassword() == null || !encryptionManager.hashMatches(email.getPassword(), getEffectiveProfile().getPassword())) {
errors.add(getMessage("check_password_modal.incorrect_password"));
}
if (errors.isEmpty()) {
String newPrime = null;
String oldPrime = null;
List<String> emailErrors = new ArrayList<String>();
// clear errros
email.setErrors(new ArrayList<String>());
// if blank
if (email.getValue() == null || email.getValue().trim().equals("")) {
emailErrors.add(getMessage("Email.personalInfoForm.email"));
}
OrcidProfile currentProfile = getEffectiveProfile();
List<Email> emails = currentProfile.getOrcidBio().getContactDetails().getEmail();
MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email");
// make sure there are no dups
validateEmailAddress(email.getValue(), false, request, mbr);
for (ObjectError oe : mbr.getAllErrors()) {
emailErrors.add(getMessage(oe.getCode(), email.getValue()));
}
email.setErrors(emailErrors);
if (emailErrors.size() == 0) {
if (email.isPrimary()) {
for (Email curEmail : emails) {
if (curEmail.isPrimary())
oldPrime = curEmail.getValue();
curEmail.setPrimary(false);
}
newPrime = email.getValue();
}
emails.add(email);
currentProfile.getOrcidBio().getContactDetails().setEmail(emails);
email.setSource(getRealUserOrcid());
emailManager.addEmail(currentProfile.getOrcid().getValue(), email);
// send verifcation email for new address
URI baseUri = OrcidWebUtils.getServerUriWithContextPath(request);
notificationManager.sendVerificationEmail(currentProfile, baseUri, email.getValue());
// if primary also send change notification.
if (newPrime != null && !newPrime.equalsIgnoreCase(oldPrime)) {
request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false);
notificationManager.sendEmailAddressChangedNotification(currentProfile, new Email(oldPrime), baseUri);
}
}
} else {
email.setErrors(errors);
}
return email;
}
@RequestMapping(value = "/deleteEmail.json", method = RequestMethod.DELETE)
public @ResponseBody
org.orcid.pojo.Email deleteEmailJson(HttpServletRequest request, @RequestBody org.orcid.pojo.Email email) {
List<String> emailErrors = new ArrayList<String>();
// clear errros
email.setErrors(new ArrayList<String>());
// if blank
if (email.getValue() == null || email.getValue().trim().equals("")) {
emailErrors.add(getMessage("Email.personalInfoForm.email"));
}
OrcidProfile currentProfile = getEffectiveProfile();
List<Email> emails = currentProfile.getOrcidBio().getContactDetails().getEmail();
if (email.isPrimary()) {
emailErrors.add(getMessage("manage.email.primaryEmailDeletion"));
}
email.setErrors(emailErrors);
if (emailErrors.size() == 0) {
Iterator<Email> emailIterator = emails.iterator();
while (emailIterator.hasNext()) {
Email nextEmail = emailIterator.next();
if (nextEmail.getValue().equals(email.getValue())) {
emailIterator.remove();
}
}
currentProfile.getOrcidBio().getContactDetails().setEmail(emails);
emailManager.removeEmail(currentProfile.getOrcid().getValue(), email.getValue());
}
return email;
}
@RequestMapping(value = "/emails.json", method = RequestMethod.POST)
public @ResponseBody
org.orcid.pojo.ajaxForm.Emails postEmailsJson(HttpServletRequest request, @RequestBody org.orcid.pojo.ajaxForm.Emails emails) {
org.orcid.pojo.Email newPrime = null;
org.orcid.pojo.Email oldPrime = null;
List<String> allErrors = new ArrayList<String>();
for (org.orcid.pojo.Email email : emails.getEmails()) {
MapBindingResult mbr = new MapBindingResult(new HashMap<String, String>(), "Email");
validateEmailAddress(email.getValue(), request, mbr);
List<String> emailErrors = new ArrayList<String>();
for (ObjectError oe : mbr.getAllErrors()) {
String msg = getMessage(oe.getCode(), email.getValue());
emailErrors.add(getMessage(oe.getCode(), email.getValue()));
allErrors.add(msg);
}
email.setErrors(emailErrors);
if (email.isPrimary())
newPrime = email;
}
if (newPrime == null) {
allErrors.add("A Primary Email Must be selected");
}
OrcidProfile currentProfile = getEffectiveProfile();
if (currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail() != null)
oldPrime = new org.orcid.pojo.Email(currentProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail());
emails.setErrors(allErrors);
if (allErrors.size() == 0) {
currentProfile.getOrcidBio().getContactDetails().setEmail((List<Email>) (Object) emails.getEmails());
emailManager.updateEmails(currentProfile.getOrcid().getValue(), currentProfile.getOrcidBio().getContactDetails().getEmail());
if (newPrime != null && !newPrime.getValue().equalsIgnoreCase(oldPrime.getValue())) {
URI baseUri = OrcidWebUtils.getServerUriWithContextPath(request);
notificationManager.sendEmailAddressChangedNotification(currentProfile, new Email(oldPrime.getValue()), baseUri);
if (!newPrime.isVerified()) {
notificationManager.sendVerificationEmail(currentProfile, baseUri, newPrime.getValue());
request.getSession().setAttribute(ManageProfileController.CHECK_EMAIL_VALIDATED, false);
}
}
}
return emails;
}
@RequestMapping(value = "/save-bio-settings", method = RequestMethod.POST)
public ModelAndView saveEditedBio(HttpServletRequest request, @Valid @ModelAttribute("changePersonalInfoForm") ChangePersonalInfoForm changePersonalInfoForm,
BindingResult bindingResult, RedirectAttributes redirectAttributes) {
- ModelAndView manageBioView = new ModelAndView("redirect:manage-bio-settings");
+ ModelAndView manageBioView = new ModelAndView("redirect:/account/manage-bio-settings");
for (String keyword : changePersonalInfoForm.getKeywordsAsList()) {
if (keyword.length() > ChangePersonalInfoForm.KEYWORD_MAX_LEN) {
bindingResult.rejectValue("keywordsDelimited", "Length.changePersonalInfoForm.keywordsDelimited");
break;
}
}
if (bindingResult.hasErrors()) {
ModelAndView erroredView = new ModelAndView("manage_bio_settings");
// If an error happens and the user doesnt have any website,
// the privacy selector for websites dissapears.
// In order to fix this, if the ChangePersonalInfoForm doesnt have
// any researcher url, we add a new one with an empty list, which
// is different than null ResearcherUrls
Map<String, Object> model = bindingResult.getModel();
if (changePersonalInfoForm.getSavedResearcherUrls() == null) {
changePersonalInfoForm.setSavedResearcherUrls(new ResearcherUrls());
}
model.put("changePersonalInfoForm", changePersonalInfoForm);
erroredView.addAllObjects(bindingResult.getModel());
return erroredView;
}
OrcidProfile profile = getEffectiveProfile();
// Update profile with values that comes from user request
changePersonalInfoForm.mergeOrcidBioDetails(profile);
// Update profile on database
profileEntityManager.updateProfile(profile);
String orcid = profile.getOrcid().getValue();
// Update other names on database
OtherNames otherNames = profile.getOrcidBio().getPersonalDetails().getOtherNames();
otherNameManager.updateOtherNames(orcid, otherNames);
// Update keywords on database
Keywords keywords = profile.getOrcidBio().getKeywords();
profileKeywordManager.updateProfileKeyword(orcid, keywords);
// Update researcher urls on database
ResearcherUrls researcherUrls = profile.getOrcidBio().getResearcherUrls();
boolean hasErrors = researcherUrlManager.updateResearcherUrls(orcid, researcherUrls);
// TODO: The researcherUrlManager will not store any duplicated
// researcher url on database,
// however there is no way to tell the controller that some of the
// researcher urls were not
// saved, so, if an error occurs, we need to reload researcher ids from
// database and update
// cached profile. A more efficient way to fix this might be used.
if (hasErrors) {
ResearcherUrls upToDateResearcherUrls = getUpToDateResearcherUrls(orcid, researcherUrls.getVisibility());
profile.getOrcidBio().setResearcherUrls(upToDateResearcherUrls);
}
redirectAttributes.addFlashAttribute("changesSaved", true);
return manageBioView;
}
/**
* Generate an up to date ResearcherUrls object.
*
* @param orcid
* @param visibility
* */
private ResearcherUrls getUpToDateResearcherUrls(String orcid, Visibility visibility) {
ResearcherUrls upTodateResearcherUrls = new ResearcherUrls();
upTodateResearcherUrls.setVisibility(visibility);
List<ResearcherUrlEntity> upToDateResearcherUrls = researcherUrlManager.getResearcherUrls(orcid);
for (ResearcherUrlEntity researcherUrlEntity : upToDateResearcherUrls) {
ResearcherUrl newResearcherUrl = new ResearcherUrl();
newResearcherUrl.setUrl(new Url(researcherUrlEntity.getUrl()));
newResearcherUrl.setUrlName(new UrlName(researcherUrlEntity.getUrlName()));
upTodateResearcherUrls.getResearcherUrl().add(newResearcherUrl);
}
return upTodateResearcherUrls;
}
}
| true | true | public ModelAndView saveEditedBio(HttpServletRequest request, @Valid @ModelAttribute("changePersonalInfoForm") ChangePersonalInfoForm changePersonalInfoForm,
BindingResult bindingResult, RedirectAttributes redirectAttributes) {
ModelAndView manageBioView = new ModelAndView("redirect:manage-bio-settings");
for (String keyword : changePersonalInfoForm.getKeywordsAsList()) {
if (keyword.length() > ChangePersonalInfoForm.KEYWORD_MAX_LEN) {
bindingResult.rejectValue("keywordsDelimited", "Length.changePersonalInfoForm.keywordsDelimited");
break;
}
}
if (bindingResult.hasErrors()) {
ModelAndView erroredView = new ModelAndView("manage_bio_settings");
// If an error happens and the user doesnt have any website,
// the privacy selector for websites dissapears.
// In order to fix this, if the ChangePersonalInfoForm doesnt have
// any researcher url, we add a new one with an empty list, which
// is different than null ResearcherUrls
Map<String, Object> model = bindingResult.getModel();
if (changePersonalInfoForm.getSavedResearcherUrls() == null) {
changePersonalInfoForm.setSavedResearcherUrls(new ResearcherUrls());
}
model.put("changePersonalInfoForm", changePersonalInfoForm);
erroredView.addAllObjects(bindingResult.getModel());
return erroredView;
}
OrcidProfile profile = getEffectiveProfile();
// Update profile with values that comes from user request
changePersonalInfoForm.mergeOrcidBioDetails(profile);
// Update profile on database
profileEntityManager.updateProfile(profile);
String orcid = profile.getOrcid().getValue();
// Update other names on database
OtherNames otherNames = profile.getOrcidBio().getPersonalDetails().getOtherNames();
otherNameManager.updateOtherNames(orcid, otherNames);
// Update keywords on database
Keywords keywords = profile.getOrcidBio().getKeywords();
profileKeywordManager.updateProfileKeyword(orcid, keywords);
// Update researcher urls on database
ResearcherUrls researcherUrls = profile.getOrcidBio().getResearcherUrls();
boolean hasErrors = researcherUrlManager.updateResearcherUrls(orcid, researcherUrls);
// TODO: The researcherUrlManager will not store any duplicated
// researcher url on database,
// however there is no way to tell the controller that some of the
// researcher urls were not
// saved, so, if an error occurs, we need to reload researcher ids from
// database and update
// cached profile. A more efficient way to fix this might be used.
if (hasErrors) {
ResearcherUrls upToDateResearcherUrls = getUpToDateResearcherUrls(orcid, researcherUrls.getVisibility());
profile.getOrcidBio().setResearcherUrls(upToDateResearcherUrls);
}
redirectAttributes.addFlashAttribute("changesSaved", true);
return manageBioView;
}
| public ModelAndView saveEditedBio(HttpServletRequest request, @Valid @ModelAttribute("changePersonalInfoForm") ChangePersonalInfoForm changePersonalInfoForm,
BindingResult bindingResult, RedirectAttributes redirectAttributes) {
ModelAndView manageBioView = new ModelAndView("redirect:/account/manage-bio-settings");
for (String keyword : changePersonalInfoForm.getKeywordsAsList()) {
if (keyword.length() > ChangePersonalInfoForm.KEYWORD_MAX_LEN) {
bindingResult.rejectValue("keywordsDelimited", "Length.changePersonalInfoForm.keywordsDelimited");
break;
}
}
if (bindingResult.hasErrors()) {
ModelAndView erroredView = new ModelAndView("manage_bio_settings");
// If an error happens and the user doesnt have any website,
// the privacy selector for websites dissapears.
// In order to fix this, if the ChangePersonalInfoForm doesnt have
// any researcher url, we add a new one with an empty list, which
// is different than null ResearcherUrls
Map<String, Object> model = bindingResult.getModel();
if (changePersonalInfoForm.getSavedResearcherUrls() == null) {
changePersonalInfoForm.setSavedResearcherUrls(new ResearcherUrls());
}
model.put("changePersonalInfoForm", changePersonalInfoForm);
erroredView.addAllObjects(bindingResult.getModel());
return erroredView;
}
OrcidProfile profile = getEffectiveProfile();
// Update profile with values that comes from user request
changePersonalInfoForm.mergeOrcidBioDetails(profile);
// Update profile on database
profileEntityManager.updateProfile(profile);
String orcid = profile.getOrcid().getValue();
// Update other names on database
OtherNames otherNames = profile.getOrcidBio().getPersonalDetails().getOtherNames();
otherNameManager.updateOtherNames(orcid, otherNames);
// Update keywords on database
Keywords keywords = profile.getOrcidBio().getKeywords();
profileKeywordManager.updateProfileKeyword(orcid, keywords);
// Update researcher urls on database
ResearcherUrls researcherUrls = profile.getOrcidBio().getResearcherUrls();
boolean hasErrors = researcherUrlManager.updateResearcherUrls(orcid, researcherUrls);
// TODO: The researcherUrlManager will not store any duplicated
// researcher url on database,
// however there is no way to tell the controller that some of the
// researcher urls were not
// saved, so, if an error occurs, we need to reload researcher ids from
// database and update
// cached profile. A more efficient way to fix this might be used.
if (hasErrors) {
ResearcherUrls upToDateResearcherUrls = getUpToDateResearcherUrls(orcid, researcherUrls.getVisibility());
profile.getOrcidBio().setResearcherUrls(upToDateResearcherUrls);
}
redirectAttributes.addFlashAttribute("changesSaved", true);
return manageBioView;
}
|
diff --git a/src/de/fabianonline/geotweeter/timelineelements/Tweet.java b/src/de/fabianonline/geotweeter/timelineelements/Tweet.java
index cb084fa..5d908b2 100644
--- a/src/de/fabianonline/geotweeter/timelineelements/Tweet.java
+++ b/src/de/fabianonline/geotweeter/timelineelements/Tweet.java
@@ -1,150 +1,150 @@
package de.fabianonline.geotweeter.timelineelements;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import android.graphics.drawable.Drawable;
import android.view.View;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import de.fabianonline.geotweeter.Constants;
import de.fabianonline.geotweeter.R;
import de.fabianonline.geotweeter.User;
import de.fabianonline.geotweeter.activities.TimelineActivity;
public class Tweet extends TimelineElement{
private static final long serialVersionUID = -6610449879010917836L;
private static final String LOG = "Tweet";
public String text;
public String text_for_display = null;
public long id;
public User user;
public View view;
public String source;
public JSONObject entities;
public long getID() {
return id;
}
public String getTextForDisplay() {
if (text_for_display == null) {
if (entities == null) {
// TODO why?
text_for_display = new String(text);
} else {
StringBuilder temp_text = new StringBuilder();
JSONArray urls = entities.getJSONArray("urls");
int start_index = 0;
if (urls!=null) {
for (int i=0; i<urls.size(); i++) {
JSONObject url = urls.getJSONObject(i);
JSONArray indices = url.getJSONArray("indices");
temp_text.append(text.substring(start_index, indices.getIntValue(0)));
temp_text.append(url.getString("display_url"));
start_index = indices.getIntValue(1);
}
if(start_index < text.length()) {
- temp_text.append(text.substring(start_index, text.length()-1));
+ temp_text.append(text.substring(start_index, text.length()));
}
text_for_display = temp_text.toString();
} else {
text_for_display = new String(text);
}
}
}
return "<strong>" + user.getScreenName() + "</strong> " + text_for_display;
}
public void setUser(User u) {
if(User.all_users.containsKey(u.id)) {
user = User.all_users.get(u.id);
} else {
User.all_users.put(u.id, u);
user = u;
}
}
public String getAvatarSource() {
return user.getAvatarSource();
}
public void setSource(String str) {
Matcher m = Constants.REGEXP_FIND_SOURCE.matcher(str);
if (m.find()) {
source = m.group(1);
} else {
source = "web";
}
}
public Drawable getAvatarDrawable() { return user.avatar; }
public CharSequence getSourceText() { return new SimpleDateFormat("dd.MM. HH:mm").format(created_at) + " from " + source; }
public String getSenderScreenName() {
return user.getScreenName();
}
@Override
public boolean isReplyable() {
return true;
}
@Override
public boolean showNotification() {
return true;
}
@Override
public String getNotificationText(String type) {
if (type.equals("mention")) {
return "Mention von " + user.screen_name + ": " + text;
} else if (type.equals("retweet")) {
return user.screen_name + " retweetete: " + text;
}
return "";
}
@Override
public String getNotificationContentTitle(String type) {
if (type.equals("mention")) {
return "Mention von " + user.screen_name;
} else if(type.equals("retweet")) {
return "Retweet von " + user.screen_name;
}
return "";
}
@Override
public String getNotificationContentText(String type) {
return text;
}
@Override
public int getBackgroundDrawableID() {
User current_user = TimelineActivity.current_account.getUser();
if (user.id == current_user.id) {
return R.drawable.listelement_background_my;
} else if(this.mentionsUser(current_user)) {
return R.drawable.listelement_background_mention;
} else if(this.id > TimelineActivity.current_account.getMaxReadTweetID()) {
return R.drawable.listelement_background_unread;
} else {
return R.drawable.listelement_background_normal;
}
}
public boolean mentionsUser(User user) {
if (entities!=null) {
JSONArray mentions = entities.getJSONArray("user_mentions");
for(int i=0; i<mentions.size(); i++) {
if (mentions.getJSONObject(i).getLong("id").equals(user.id)) {
return true;
}
}
}
return false;
}
}
| true | true | public String getTextForDisplay() {
if (text_for_display == null) {
if (entities == null) {
// TODO why?
text_for_display = new String(text);
} else {
StringBuilder temp_text = new StringBuilder();
JSONArray urls = entities.getJSONArray("urls");
int start_index = 0;
if (urls!=null) {
for (int i=0; i<urls.size(); i++) {
JSONObject url = urls.getJSONObject(i);
JSONArray indices = url.getJSONArray("indices");
temp_text.append(text.substring(start_index, indices.getIntValue(0)));
temp_text.append(url.getString("display_url"));
start_index = indices.getIntValue(1);
}
if(start_index < text.length()) {
temp_text.append(text.substring(start_index, text.length()-1));
}
text_for_display = temp_text.toString();
} else {
text_for_display = new String(text);
}
}
}
return "<strong>" + user.getScreenName() + "</strong> " + text_for_display;
}
| public String getTextForDisplay() {
if (text_for_display == null) {
if (entities == null) {
// TODO why?
text_for_display = new String(text);
} else {
StringBuilder temp_text = new StringBuilder();
JSONArray urls = entities.getJSONArray("urls");
int start_index = 0;
if (urls!=null) {
for (int i=0; i<urls.size(); i++) {
JSONObject url = urls.getJSONObject(i);
JSONArray indices = url.getJSONArray("indices");
temp_text.append(text.substring(start_index, indices.getIntValue(0)));
temp_text.append(url.getString("display_url"));
start_index = indices.getIntValue(1);
}
if(start_index < text.length()) {
temp_text.append(text.substring(start_index, text.length()));
}
text_for_display = temp_text.toString();
} else {
text_for_display = new String(text);
}
}
}
return "<strong>" + user.getScreenName() + "</strong> " + text_for_display;
}
|
diff --git a/library/src/de/alosdev/android/customerschoice/VariantBuilder.java b/library/src/de/alosdev/android/customerschoice/VariantBuilder.java
index 7985bad..df4e1d6 100644
--- a/library/src/de/alosdev/android/customerschoice/VariantBuilder.java
+++ b/library/src/de/alosdev/android/customerschoice/VariantBuilder.java
@@ -1,107 +1,107 @@
/*
* Copyright 2012 Hasan Hosgel
*
* 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.alosdev.android.customerschoice;
import java.util.Date;
/**
* The {@link VariantBuilder} is like the name defines a builder for the {@link Variant}, so you can freely configure
* your variant and if you finished you can build the final {@link Variant}. The Builder implments a fluent interface,
* so you can go through it like the append in {@link StringBuilder}.
* @author Hasan Hosgel
*
*/
public class VariantBuilder {
private String name;
private long startTime = 0;
private long endTime = Long.MAX_VALUE;
private int[] spreading = { 1 };
public VariantBuilder(String name) {
setName(name);
}
/**
* sets the name
* @param name
*/
public VariantBuilder setName(String name) {
- if ((null == name) || (name.length() > 0)) {
- throw new IllegalArgumentException("The name must contains at least onw char");
+ if ((null == name) || (name.length() < 1)) {
+ throw new IllegalArgumentException("The name must contains at least one char");
}
this.name = name;
return this;
}
/**
* adds an startdate for the variant
* @param startDate
* @return
*/
public VariantBuilder setStartDate(Date startDate) {
startTime = startDate.getTime();
return this;
}
/**
* adds an starttime for the variant
* @param starttime in milliseconds
* @return
*/
public VariantBuilder setStartTime(long startTime) {
this.startTime = startTime;
return this;
}
/**
* adds the enddate for the variant
* @param endDate
* @return
*/
public VariantBuilder setEndDate(Date endDate) {
endTime = endDate.getTime();
return this;
}
/**
* adds the endtime for the variant
* @param endTime in milliseconds
* @return
*/
public VariantBuilder setEndTime(long endTime) {
this.endTime = endTime;
return this;
}
/**
* the the spreading/ variation of the variant
* @param spreading
* @return
*/
public VariantBuilder setSpreading(int[] spreading) {
this.spreading = spreading;
return this;
}
/**
* creates the {@link Variant} after configuring it completely.
* @return
*/
public Variant build() {
return new Variant(name, startTime, endTime, spreading);
}
}
| true | true | public VariantBuilder setName(String name) {
if ((null == name) || (name.length() > 0)) {
throw new IllegalArgumentException("The name must contains at least onw char");
}
this.name = name;
return this;
}
| public VariantBuilder setName(String name) {
if ((null == name) || (name.length() < 1)) {
throw new IllegalArgumentException("The name must contains at least one char");
}
this.name = name;
return this;
}
|
diff --git a/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java b/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java
index 90c53c96..0f5eec6b 100644
--- a/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java
+++ b/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java
@@ -1,155 +1,155 @@
/*
* 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.vfs2.provider.http;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* Create a HttpClient instance.
*/
public final class HttpClientFactory
{
private HttpClientFactory()
{
}
public static HttpClient createConnection(String scheme, String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return createConnection(HttpFileSystemConfigBuilder.getInstance(), scheme, hostname, port,
username, password, fileSystemOptions);
}
/**
* Creates a new connection to the server.
* @param builder The HttpFileSystemConfigBuilder.
* @param scheme The protocol.
* @param hostname The hostname.
* @param port The port number.
* @param username The username.
* @param password The password
* @param fileSystemOptions The file system options.
* @return a new HttpClient connection.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme,
String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
HttpClient client;
try
{
HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams connectionMgrParams = mgr.getParams();
client = new HttpClient(mgr);
final HostConfiguration config = new HostConfiguration();
config.setHost(hostname, port, scheme);
if (fileSystemOptions != null)
{
String proxyHost = builder.getProxyHost(fileSystemOptions);
int proxyPort = builder.getProxyPort(fileSystemOptions);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0)
{
config.setProxy(proxyHost, proxyPort);
}
UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
if (proxyAuth != null)
{
UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME,
UserAuthenticationData.PASSWORD
});
if (authData != null)
{
final UsernamePasswordCredentials proxyCreds =
new UsernamePasswordCredentials(
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, null)),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, null)));
AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
client.getState().setProxyCredentials(scope, proxyCreds);
}
if (builder.isPreemptiveAuth(fileSystemOptions))
{
HttpClientParams httpClientParams = new HttpClientParams();
httpClientParams.setAuthenticationPreemptive(true);
client.setParams(httpClientParams);
}
}
Cookie[] cookies = builder.getCookies(fileSystemOptions);
if (cookies != null)
{
client.getState().addCookies(cookies);
}
}
/**
- * ConnectionManager set methodsmust be called after the host & port and proxy host & port
+ * ConnectionManager set methods must be called after the host & port and proxy host & port
* are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
* tries to locate the host configuration.
*/
connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions));
connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));
client.setHostConfiguration(config);
if (username != null)
{
final UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(username, password);
AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
client.getState().setCredentials(scope, creds);
}
client.executeMethod(new HeadMethod());
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
}
return client;
}
}
| true | true | public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme,
String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
HttpClient client;
try
{
HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams connectionMgrParams = mgr.getParams();
client = new HttpClient(mgr);
final HostConfiguration config = new HostConfiguration();
config.setHost(hostname, port, scheme);
if (fileSystemOptions != null)
{
String proxyHost = builder.getProxyHost(fileSystemOptions);
int proxyPort = builder.getProxyPort(fileSystemOptions);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0)
{
config.setProxy(proxyHost, proxyPort);
}
UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
if (proxyAuth != null)
{
UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME,
UserAuthenticationData.PASSWORD
});
if (authData != null)
{
final UsernamePasswordCredentials proxyCreds =
new UsernamePasswordCredentials(
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, null)),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, null)));
AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
client.getState().setProxyCredentials(scope, proxyCreds);
}
if (builder.isPreemptiveAuth(fileSystemOptions))
{
HttpClientParams httpClientParams = new HttpClientParams();
httpClientParams.setAuthenticationPreemptive(true);
client.setParams(httpClientParams);
}
}
Cookie[] cookies = builder.getCookies(fileSystemOptions);
if (cookies != null)
{
client.getState().addCookies(cookies);
}
}
/**
* ConnectionManager set methodsmust be called after the host & port and proxy host & port
* are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
* tries to locate the host configuration.
*/
connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions));
connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));
client.setHostConfiguration(config);
if (username != null)
{
final UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(username, password);
AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
client.getState().setCredentials(scope, creds);
}
client.executeMethod(new HeadMethod());
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
}
return client;
}
| public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme,
String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
HttpClient client;
try
{
HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams connectionMgrParams = mgr.getParams();
client = new HttpClient(mgr);
final HostConfiguration config = new HostConfiguration();
config.setHost(hostname, port, scheme);
if (fileSystemOptions != null)
{
String proxyHost = builder.getProxyHost(fileSystemOptions);
int proxyPort = builder.getProxyPort(fileSystemOptions);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0)
{
config.setProxy(proxyHost, proxyPort);
}
UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
if (proxyAuth != null)
{
UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME,
UserAuthenticationData.PASSWORD
});
if (authData != null)
{
final UsernamePasswordCredentials proxyCreds =
new UsernamePasswordCredentials(
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, null)),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, null)));
AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
client.getState().setProxyCredentials(scope, proxyCreds);
}
if (builder.isPreemptiveAuth(fileSystemOptions))
{
HttpClientParams httpClientParams = new HttpClientParams();
httpClientParams.setAuthenticationPreemptive(true);
client.setParams(httpClientParams);
}
}
Cookie[] cookies = builder.getCookies(fileSystemOptions);
if (cookies != null)
{
client.getState().addCookies(cookies);
}
}
/**
* ConnectionManager set methods must be called after the host & port and proxy host & port
* are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
* tries to locate the host configuration.
*/
connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions));
connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));
client.setHostConfiguration(config);
if (username != null)
{
final UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(username, password);
AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
client.getState().setCredentials(scope, creds);
}
client.executeMethod(new HeadMethod());
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
}
return client;
}
|
diff --git a/src/main/java/hudson/scm/CVSSCM.java b/src/main/java/hudson/scm/CVSSCM.java
index 7f27d48..80363f1 100644
--- a/src/main/java/hudson/scm/CVSSCM.java
+++ b/src/main/java/hudson/scm/CVSSCM.java
@@ -1,1233 +1,1231 @@
/*
* The MIT License
*
* Copyright (c) 2004-2012, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jene Jasper, Stephen Connolly, CloudBees, Inc., Michael Clarke
*
* 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.scm;
import static hudson.Util.fixEmptyAndTrim;
import static hudson.Util.fixNull;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.FilePath.FileCallable;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Describable;
import hudson.model.ModelObject;
import hudson.model.TaskListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.remoting.VirtualChannel;
import hudson.scm.CVSChangeLogSet.CVSChangeLog;
import hudson.scm.cvstagging.CvsTagAction;
import hudson.scm.cvstagging.LegacyTagAction;
import hudson.util.Secret;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.export.Exported;
import org.netbeans.lib.cvsclient.CVSRoot;
import org.netbeans.lib.cvsclient.Client;
import org.netbeans.lib.cvsclient.admin.AdminHandler;
import org.netbeans.lib.cvsclient.admin.Entry;
import org.netbeans.lib.cvsclient.admin.StandardAdminHandler;
import org.netbeans.lib.cvsclient.command.Command;
import org.netbeans.lib.cvsclient.command.CommandAbortedException;
import org.netbeans.lib.cvsclient.command.CommandException;
import org.netbeans.lib.cvsclient.command.GlobalOptions;
import org.netbeans.lib.cvsclient.command.checkout.CheckoutCommand;
import org.netbeans.lib.cvsclient.command.log.RlogCommand;
import org.netbeans.lib.cvsclient.command.update.UpdateCommand;
import org.netbeans.lib.cvsclient.commandLine.BasicListener;
import org.netbeans.lib.cvsclient.connection.AuthenticationException;
import org.netbeans.lib.cvsclient.connection.Connection;
import org.netbeans.lib.cvsclient.connection.ConnectionFactory;
import org.netbeans.lib.cvsclient.connection.ConnectionIdentity;
import org.netbeans.lib.cvsclient.event.CVSListener;
/**
* CVS.
*
* <p>
* I couldn't call this class "CVS" because that would cause the view folder
* name to collide with CVS control files.
*
* <p>
* This object gets shipped to the remote machine to perform some of the work,
* so it implements {@link Serializable}.
*
* @author Kohsuke Kawaguchi
* @author Michael Clarke
*/
public class CVSSCM extends SCM implements Serializable {
private static final long serialVersionUID = -2175193493227149541L;
private static final DateFormat DATE_FORMATTER = new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.UK);
/**
* True to avoid creating a sub-directory inside the workspace. (Works only
* when there's just one repository containing one module.)
*/
private final boolean flatten;
private CVSRepositoryBrowser repositoryBrowser;
private final CvsRepository[] repositories;
private final boolean canUseUpdate;
private final boolean skipChangeLog;
private boolean pruneEmptyDirectories;
private boolean disableCvsQuiet;
private boolean cleanOnFailedUpdate;
// start legacy fields
@Deprecated
private transient String module;
@Deprecated
private transient String cvsroot;
@Deprecated
private transient String branch;
@Deprecated
private transient boolean useHeadIfNotFound;
@Deprecated
private transient boolean isTag;
@Deprecated
private transient String excludedRegions;
@Deprecated
private transient String cvsRsh;
// end legacy fields
/**
* @deprecated we now use multiple repositories and don't use cvsRsh
*/
@Deprecated
public CVSSCM(final String cvsRoot, final String allModules, final String branch, final String cvsRsh,
final boolean canUseUpdate, final boolean useHeadIfNotFound, final boolean legacy,
final boolean isTag, final String excludedRegions) {
this(LegacyConvertor.getInstance().convertLegacyConfigToRepositoryStructure(cvsRoot, allModules, branch, isTag, excludedRegions,
useHeadIfNotFound), canUseUpdate, legacy, null, Boolean.getBoolean(CVSSCM.class.getName() + ".skipChangeLog"), true, false, false);
}
@DataBoundConstructor
public CVSSCM(final List<CvsRepository> repositories, final boolean canUseUpdate, final boolean legacy,
final CVSRepositoryBrowser browser, final boolean skipChangeLog, final boolean pruneEmptyDirectories,
final boolean disableCvsQuiet, final boolean cleanOnFailedUpdate) {
this.repositories = repositories.toArray(new CvsRepository[repositories.size()]);
this.canUseUpdate = canUseUpdate;
this.skipChangeLog = skipChangeLog;
flatten = !legacy && this.repositories.length == 1 && this.repositories[0].getRepositoryItems().length == 0 && this.repositories[0].getRepositoryItems()[0].getModules().length == 1 && "".equals(fixNull(this.repositories[0].getRepositoryItems()[0].getModules()[0].getLocalName()));
repositoryBrowser = browser;
this.pruneEmptyDirectories = pruneEmptyDirectories;
this.disableCvsQuiet = disableCvsQuiet;
this.cleanOnFailedUpdate = cleanOnFailedUpdate;
}
/**
* Convert legacy configuration into the new class structure.
*
* @return an instance of this class with all the new fields transferred
* from the old structure to the new one
*/
public final Object readResolve() {
/*
* check if we're running a version of this class that uses multiple
* repositories. if we are then we can return it as it is
*/
if (null != repositories) {
return this;
}
/*
* if we've got to this point then we have to do some conversion. Do
* this by using the deprecated constructor to upgrade the model through
* constructor chaining
*/
return new CVSSCM(cvsroot, module, branch, cvsRsh, isCanUseUpdate(), useHeadIfNotFound, isLegacy(), isTag,
excludedRegions);
}
/**
* Calculates the level of compression that should be used for dealing with
* the given repository.
* <p>
* If we're using a local repository then we don't use compression
* (http://root.cern.ch/root/CVS.html#checkout), if no compression level has
* been specifically set for this repository then we use the global setting,
* otherwise we use the one set for this repository.
*
* @param repository
* the repository we're wanting to connect to
* @return the level of compression to use between 0 and 9 (inclusive), with
* 0 being no compression and 9 being maximum
*/
private int getCompressionLevel(final CvsRepository repository, final EnvVars envVars) {
final String cvsroot = envVars.expand(repository.getCvsRoot());
/*
* CVS 1.11.22 manual: If the access method is omitted, then if the
* repository starts with `/', then `:local:' is assumed. If it does not
* start with `/' then either `:ext:' or `:server:' is assumed.
*/
boolean local = cvsroot.startsWith("/") || cvsroot.startsWith(":local:") || cvsroot.startsWith(":fork:");
// Use whatever the user has specified as the system default if the
// repository doesn't specifically set one
int compressionLevel = repository.getCompressionLevel() == -1 ? getDescriptor().getCompressionLevel()
: repository.getCompressionLevel();
// For local access, compression is senseless (always return 0),
// otherwise return the calculated value
return local ? 0 : compressionLevel;
}
/**
* Gets the repositories currently configured for this job.
*
* @return an array of {@link CvsRepository}
*/
@Exported
public CvsRepository[] getRepositories() {
return repositories;
}
@Override
public CVSRepositoryBrowser getBrowser() {
return repositoryBrowser;
}
@Override
public boolean requiresWorkspaceForPolling() {
return false;
}
/**
* Since we add the current SCMRevisionState as an action during the build
* (so we can get the current workspace state), this method should never be
* called. Just for safety, we get the action and return it.
*
* @see {@link SCM#calcRevisionsFromBuild(AbstractBuild, Launcher, TaskListener)}
*/
@Override
public SCMRevisionState calcRevisionsFromBuild(final AbstractBuild<?, ?> build, final Launcher launcher,
final TaskListener listener) throws IOException, InterruptedException {
return build.getAction(CvsRevisionState.class);
}
/**
* Checks for differences between the current workspace and the remote
* repository.
*
* @see {@link SCM#compareRemoteRevisionWith(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}
*/
@Override
protected PollingResult compareRemoteRevisionWith(final AbstractProject<?, ?> project, final Launcher launcher,
final FilePath workspace, final TaskListener listener, final SCMRevisionState baseline)
throws IOException, InterruptedException {
// No previous build? everything has changed
if (null == project.getLastBuild()) {
listener.getLogger().println("No previous build found, scheduling build");
return PollingResult.BUILD_NOW;
}
final EnvVars envVars = project.getLastBuild().getEnvironment(listener);
final Date currentPollDate = Calendar.getInstance().getTime();
/*
* this flag will be used to check whether a build is needed (assuming
* the local and remote states are comparable and no configuration has
* changed between the last build and the current one)
*/
boolean changesPresent = false;
// Schedule a new build if the baseline isn't valid
if ((baseline == null || !(baseline instanceof CvsRevisionState))) {
listener.getLogger().println("Invalid baseline detected, scheduling build");
return new PollingResult(baseline, new CvsRevisionState(new HashMap<CvsRepository, List<CvsFile>>()),
PollingResult.Change.INCOMPARABLE);
}
// convert the baseline into a use-able form
final Map<CvsRepository, List<CvsFile>> remoteState = new HashMap<CvsRepository, List<CvsFile>>(
((CvsRevisionState) baseline).getModuleFiles());
// Loops through every module and check if it has changed
for (CvsRepository repository : repositories) {
/*
* this repository setting either didn't exist or has changed since
* the last build so we'll force a new build now.
*/
if (!remoteState.containsKey(repository)) {
listener.getLogger().println("Repository not found in workspace state, scheduling build");
return new PollingResult(baseline, new CvsRevisionState(new HashMap<CvsRepository, List<CvsFile>>()),
PollingResult.Change.INCOMPARABLE);
}
// get the list of current changed files in this repository
final List<CvsFile> changes = calculateRepositoryState(project.getLastCompletedBuild().getTime(),
currentPollDate, repository, launcher, workspace, listener, envVars);
final List<CvsFile> remoteFiles = remoteState.get(repository);
// update the remote state with the changes we've just retrieved
for (CvsFile changedFile : changes) {
for (CvsFile existingFile : remoteFiles) {
if (!changedFile.getName().equals(existingFile.getName())) {
continue;
}
remoteFiles.remove(existingFile);
if (!changedFile.isDead()) {
remoteFiles.add(changedFile);
}
}
}
// set the updated files list back into the remote state
remoteState.put(repository, remoteFiles);
// convert the excluded regions into patterns so we can use them as
// regular expressions
final List<Pattern> excludePatterns = new ArrayList<Pattern>();
for (ExcludedRegion pattern : repository.getExcludedRegions()) {
try {
excludePatterns.add(Pattern.compile(pattern.getPattern()));
} catch (PatternSyntaxException ex) {
launcher.getListener().getLogger().println("Pattern could not be compiled: " + ex.getMessage());
}
}
// create a list of changes we can use to filter out excluded
// regions
final List<CvsFile> filteredChanges = new ArrayList<CvsFile>(changes);
// filter out all changes in the exclude regions
for (final Pattern excludePattern : excludePatterns) {
for (Iterator<CvsFile> itr = filteredChanges.iterator(); itr.hasNext(); ) {
CvsFile change = itr.next();
if (excludePattern.matcher(change.getName()).matches()) {
itr.remove();
}
}
}
// if our list of changes isn't empty then we want to note this as
// we need a build
changesPresent = changesPresent || !filteredChanges.isEmpty();
}
// Return the new repository state and whether we require a new build
return new PollingResult(baseline, new CvsRevisionState(remoteState),
changesPresent ? PollingResult.Change.SIGNIFICANT : PollingResult.Change.NONE);
}
/**
* Builds a list of changes that have occurred in the given repository
* between any 2 time-stamps. This does not require the workspace to be
* checked out and does not change the state of any checked out workspace.
* The list returned does not have any filters set for exclude regions (i.e.
* it's every file that's changed for the modules being watched).
*
* @param startTime
* the time-stamp to start filtering changes from
* @param endTime
* the time-stamp to end filtering changes from
* @param repository
* the repository to search for changes in. All modules under
* this repository will be checked
* @param launcher
* the executor to use when running the CVS command
* @param workspace
* the folder to use as the root directory when running the
* command
* @param listener
* where to send log output
* @return a list of changed files, including their versions and change
* comments
* @throws IOException
* on communication failure (e.g. communication with slaves)
* @throws InterruptedException
* on job cancellation
*/
private List<CVSChangeLog> calculateChangeLog(final Date startTime, final Date endTime,
final CvsRepository repository, final Launcher launcher, final FilePath workspace,
final TaskListener listener, final EnvVars envVars) throws IOException, InterruptedException {
final List<CVSChangeLog> changes = new ArrayList<CVSChangeLog>();
for (final CvsRepositoryItem item : repository.getRepositoryItems()) {
for (final CvsModule module : item.getModules()) {
String logContents = getRemoteLogForModule(repository, item, module, listener.getLogger(), startTime, endTime, envVars);
// use the parser to build up a list of changes and add it to the
// list we've been creating
changes.addAll(CvsChangeLogHelper.getInstance().mapCvsLog(logContents, repository, item, module, envVars).getChanges());
}
}
return changes;
}
/**
* Builds a list of files that have changed in the given repository between
* any 2 time-stamps. This does not require the workspace to be checked out
* and does not change the state of any checked out workspace. The list
* returned does not have any filters set for exclude regions (i.e. it's
* every file that's changed for the modules being watched).
*
* @param startTime
* the time-stamp to start filtering changes from
* @param endTime
* the time-stamp to end filtering changes from
* @param repository
* the repository to search for changes in. All modules under
* this repository will be checked
* @param launcher
* the executor to use when running the CVS command
* @param workspace
* the folder to use as the root directory when running the
* command
* @param listener
* where to send log output
* @return a list of changed files, including their versions and change
* comments
* @throws IOException
* on communication failure (e.g. communication with slaves)
* @throws InterruptedException
* on job cancellation
*/
private List<CvsFile> calculateRepositoryState(final Date startTime, final Date endTime,
final CvsRepository repository, final Launcher launcher, final FilePath workspace,
final TaskListener listener, final EnvVars envVars) throws IOException {
final List<CvsFile> files = new ArrayList<CvsFile>();
for (final CvsRepositoryItem item : repository.getRepositoryItems()) {
for (final CvsModule module : item.getModules()) {
String logContents = getRemoteLogForModule(repository, item, module, listener.getLogger(), startTime, endTime, envVars);
// use the parser to build up a list of changed files and add it to
// the list we've been creating
files.addAll(CvsChangeLogHelper.getInstance().mapCvsLog(logContents, repository, item, module, envVars).getFiles());
}
}
return files;
}
/**
* Gets the output for the CVS <tt>rlog</tt> command for the given module
* between the specified dates.
*
* @param repository
* the repository to connect to for running rlog against
* @param module
* the module to check for changes against
* @param errorStream
* where to log any error messages to
* @param startTime
* don't list any changes before this time
* @param endTime
* don't list any changes after this time
* @return the output of rlog with no modifications
* @throws IOException
* on underlying communication failure
*/
private String getRemoteLogForModule(final CvsRepository repository, final CvsRepositoryItem item, final CvsModule module,
final PrintStream errorStream, final Date startTime, final Date endTime, final EnvVars envVars) throws IOException {
final Client cvsClient = getCvsClient(repository, envVars);
RlogCommand rlogCommand = new RlogCommand();
// we have to synchronize since we're dealing with DateFormat.format()
synchronized (DATE_FORMATTER) {
final String lastBuildDate = DATE_FORMATTER.format(startTime);
final String endDate = DATE_FORMATTER.format(endTime);
rlogCommand.setDateFilter(lastBuildDate + "<" + endDate);
}
// tell CVS which module we're logging
rlogCommand.setModule(module.getRemoteName());
// ignore headers for files that aren't in the current change-set
rlogCommand.setSuppressHeader(true);
// create an output stream to send the output from CVS command to - we
// can then parse it from here
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final PrintStream logStream = new PrintStream(outputStream);
// set a listener with our output stream that we parse the log from
final CVSListener basicListener = new BasicListener(logStream, errorStream);
cvsClient.getEventManager().addCVSListener(basicListener);
// log the command to the current run/polling log
errorStream.println("cvs " + rlogCommand.getCVSCommand());
// send the command to be run, we can't continue of the task fails
try {
if (!cvsClient.executeCommand(rlogCommand, getGlobalOptions(repository, envVars))) {
throw new RuntimeException("Error while trying to run CVS rlog");
}
} catch (CommandAbortedException e) {
throw new RuntimeException("CVS rlog command aborted", e);
} catch (CommandException e) {
throw new RuntimeException("CVS rlog command failed", e);
} catch (AuthenticationException e) {
throw new RuntimeException("CVS authentication failure while running rlog command", e);
} finally {
try {
cvsClient.getConnection().close();
} catch(IOException ex) {
errorStream.println("Could not close client connection: " + ex.getMessage());
}
}
// flush the output so we have it all available for parsing
logStream.flush();
outputStream.flush();
// return the contents of the stream as the output of the command
return outputStream.toString();
}
/**
* Gets an instance of the CVS client that can be used for connection to a repository. If the
* repository specifies a password then the client's connection will be set with this password.
* @param repository the repository to connect to
* @param envVars variables to use for macro expansion
* @return a CVS client capable of connecting to the specified repository
*/
public Client getCvsClient(final CvsRepository repository, final EnvVars envVars) {
final CVSRoot cvsRoot = CVSRoot.parse(envVars.expand(repository.getCvsRoot()));
if (repository.isPasswordRequired()) {
cvsRoot.setPassword(Secret.toString(repository.getPassword()));
}
ConnectionIdentity connectionIdentity = ConnectionFactory.getConnectionIdentity();
connectionIdentity.setKnownHostsFile(envVars.expand(getDescriptor().getKnownHostsLocation()));
connectionIdentity.setPrivateKeyPath(envVars.expand(getDescriptor().getPrivateKeyLocation()));
if (getDescriptor().getPrivateKeyPassword() != null) {
connectionIdentity.setPrivateKeyPassword(getDescriptor().getPrivateKeyPassword().getPlainText());
}
final Connection cvsConnection = ConnectionFactory.getConnection(cvsRoot);
return new Client(cvsConnection, new StandardAdminHandler());
}
public GlobalOptions getGlobalOptions(CvsRepository repository, EnvVars envVars) {
final GlobalOptions globalOptions = new GlobalOptions();
globalOptions.setVeryQuiet(!disableCvsQuiet);
globalOptions.setCompressionLevel(getCompressionLevel(repository, envVars));
globalOptions.setCVSRoot(envVars.expand(repository.getCvsRoot()));
return globalOptions;
}
/**
* If there are multiple modules, return the module directory of the first
* one.
*
* @param workspace
*/
@Override
public FilePath getModuleRoot(final FilePath workspace, @SuppressWarnings("rawtypes") final AbstractBuild build) {
if (flatten) {
return workspace;
}
return workspace.child(getRepositories()[0].getRepositoryItems()[0].getModules()[0].getCheckoutName());
}
@Override
public FilePath[] getModuleRoots(final FilePath workspace, @SuppressWarnings("rawtypes") final AbstractBuild build) {
if (!flatten) {
List<FilePath> moduleRoots = new ArrayList<FilePath>();
for (CvsRepository repository : getRepositories()) {
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
for (CvsModule module : item.getModules()) {
moduleRoots.add(workspace.child(module.getCheckoutName()));
}
}
}
return moduleRoots.toArray(new FilePath[moduleRoots.size()]);
}
return new FilePath[] {getModuleRoot(workspace, build)};
}
@Override
public ChangeLogParser createChangeLogParser() {
return new CVSChangeLogParser();
}
@Exported
public boolean isCanUseUpdate() {
return canUseUpdate;
}
@Exported
public boolean isSkipChangeLog() {
return skipChangeLog;
}
@Exported
public boolean isPruneEmptyDirectories() {
return pruneEmptyDirectories;
}
@Exported
public boolean isFlatten() {
return flatten;
}
@Exported
public boolean isDisableCvsQuiet() {
return disableCvsQuiet;
}
@Exported
public boolean isCleanOnFailedUpdate() {
return cleanOnFailedUpdate;
}
public boolean isLegacy() {
return !flatten;
}
@Override
public void buildEnvVars(AbstractBuild<?,?> build, Map<String, String> env) {
String branchName = getBranchName();
if (branchName != null) {
env.put("CVS_BRANCH", branchName);
}
}
/**
* Used to support legacy setup - if we have one repository with all modules on the
* same tag/branch then this will return that tag/branch name, otherwise it will return null.
* @return a name of a tag or branch, or null if we have more than one repository or modules on different branches
*/
private String getBranchName() {
if (getRepositories()[0].getRepositoryItems()[0].getLocation().getLocationType() == CvsRepositoryLocationType.HEAD) {
return null;
}
String locationName = getRepositories()[0].getRepositoryItems()[0].getLocation().getLocationName();
if (null == locationName) {
return null;
}
for (CvsRepository repository : getRepositories()) {
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
if (!locationName.equals(item.getLocation().getLocationName())) {
return null;
}
}
}
return locationName;
}
@Override
public boolean checkout(final AbstractBuild<?, ?> build, final Launcher launcher, final FilePath workspace,
final BuildListener listener, final File changelogFile) throws IOException, InterruptedException {
if (!canUseUpdate) {
workspace.deleteContents();
}
final EnvVars envVars = build.getEnvironment(listener);
final String dateStamp;
final Date buildDate = new Date();
synchronized (DATE_FORMATTER) {
dateStamp = DATE_FORMATTER.format(buildDate);
}
for (CvsRepository repository : repositories) {
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
for (CvsModule cvsModule : item.getModules()) {
final FilePath targetWorkspace = flatten ? workspace.getParent() : workspace;
final String moduleName= flatten ? workspace.getName() : cvsModule.getCheckoutName();
final FilePath module = targetWorkspace.child(moduleName);
boolean updateFailed = false;
boolean update = false;
if (flatten) {
if (workspace.child("CVS/Entries").exists()) {
update = true;
}
} else {
if (canUseUpdate && module.exists()) {
update = true;
}
}
CvsRepositoryLocation repositoryLocation = item.getLocation();
CvsRepositoryLocationType locationType = repositoryLocation.getLocationType();
String locationName = repositoryLocation.getLocationName();
String expandedLocationName = envVars.expand(locationName);
// we're doing an update
if (update) {
// we're doing a CVS update
UpdateCommand updateCommand = new UpdateCommand();
// force it to recurse into directories
updateCommand.setBuildDirectories(true);
updateCommand.setRecursive(true);
// set directory pruning
updateCommand.setPruneDirectories(isPruneEmptyDirectories());
// point to head, branch or tag
if (locationType == CvsRepositoryLocationType.BRANCH) {
updateCommand.setUpdateByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
updateCommand.setUseHeadIfNotFound(true);
- } else {
updateCommand.setUpdateByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
updateCommand.setUpdateByRevision(expandedLocationName);
updateCommand.setUseHeadIfNotFound(repositoryLocation.isUseHeadIfNotFound());
} else {
updateCommand.setUpdateByRevision(CvsRepositoryLocationType.HEAD.getName().toUpperCase());
updateCommand.setUpdateByDate(dateStamp);
}
if (!perform(updateCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
if (cleanOnFailedUpdate) {
updateFailed = true;
} else {
return false;
}
}
}
// we're doing a checkout
if (!update || (updateFailed && cleanOnFailedUpdate)) {
if (!module.exists()) {
module.mkdirs();
}
if (updateFailed) {
listener.getLogger().println("Update failed. Cleaning workspace and performing full checkout");
workspace.deleteContents();
}
// we're doing a CVS checkout
CheckoutCommand checkoutCommand = new CheckoutCommand();
// point to branch or tag if specified
if (locationType == CvsRepositoryLocationType.BRANCH) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
- } else {
checkoutCommand.setCheckoutByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
}
} else if (locationType == CvsRepositoryLocationType.HEAD) {
checkoutCommand.setCheckoutByDate(dateStamp);
}
// set directory pruning
checkoutCommand.setPruneDirectories(isPruneEmptyDirectories());
// set where we're checking out to
checkoutCommand.setCheckoutDirectory(moduleName);
// and specify which module to load
checkoutCommand.setModule(cvsModule.getRemoteName());
if (!perform(checkoutCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
return false;
}
}
}
}
}
// build change log
final AbstractBuild<?, ?> lastCompleteBuild = build.getPreviousBuiltBuild();
if (lastCompleteBuild != null && !isSkipChangeLog()) {
final List<CVSChangeLog> changes = new ArrayList<CVSChangeLog>();
for (CvsRepository location : repositories) {
changes.addAll(calculateChangeLog(lastCompleteBuild.getTime(), build.getTime(), location, launcher,
workspace, listener, build.getEnvironment(listener)));
}
CvsChangeLogHelper.getInstance().toFile(changes, changelogFile);
}
// add the current workspace state as an action
build.getActions().add(new CvsRevisionState(calculateWorkspaceState(workspace)));
// add the tag action to the build
build.getActions().add(new CvsTagAction(build, this));
// remove sticky date tags
workspace.act(new FileCallable<Void>() {
private static final long serialVersionUID = -6867861913158282961L;
@Override
public Void invoke(final File f, final VirtualChannel channel) throws IOException {
AdminHandler adminHandler = new StandardAdminHandler();
for (File file : adminHandler.getAllFiles(f)) {
Entry entry = adminHandler.getEntry(file);
entry.setDate(null);
adminHandler.setEntry(file, entry);
}
return null;
}
});
return true;
}
/**
* Runs a cvs command in the given workspace.
* @param cvsCommand the command to run (checkout, update etc)
* @param workspace the workspace to run the command in
* @param listener where to log output to
* @param repository the repository to connect to
* @param moduleName the name of the directory within the workspace that will have work performed on it
* @param envVars the environmental variables to expand
* @return true if the action succeeds, false otherwise
* @throws IOException on failure handling files or server actions
* @throws InterruptedException if the user cancels the action
*/
private boolean perform(final Command cvsCommand, final FilePath workspace, final TaskListener listener,
final CvsRepository repository, final String moduleName, final EnvVars envVars) throws IOException, InterruptedException {
final Client cvsClient = getCvsClient(repository, envVars);
final GlobalOptions globalOptions = getGlobalOptions(repository, envVars);
if (!workspace.act(new FileCallable<Boolean>() {
private static final long serialVersionUID = -7517978923721181408L;
@Override
public Boolean invoke(final File workspace, final VirtualChannel channel) throws RuntimeException {
if (cvsCommand instanceof UpdateCommand) {
((UpdateCommand) cvsCommand).setFiles(new File[]{new File(workspace, moduleName)});
}
listener.getLogger().println("cvs " + cvsCommand.getCVSCommand());
cvsClient.setLocalPath(workspace.getAbsolutePath());
final BasicListener basicListener = new BasicListener(listener.getLogger(), listener.getLogger());
cvsClient.getEventManager().addCVSListener(basicListener);
try {
return cvsClient.executeCommand(cvsCommand, globalOptions);
} catch (CommandAbortedException e) {
e.printStackTrace(listener.error("CVS Command aborted: " + e.getMessage()));
return false;
} catch (CommandException e) {
e.printStackTrace(listener.error("CVS Command failed: " + e.getMessage()));
return false;
} catch (AuthenticationException e) {
e.printStackTrace(listener.error("CVS Authentication failed: " + e.getMessage()));
return false;
} finally {
try {
cvsClient.getConnection().close();
} catch(IOException ex) {
listener.error("Could not close client connection: " + ex.getMessage());
}
}
}
})) {
listener.error("Cvs task failed");
return false;
}
return true;
}
private Map<CvsRepository, List<CvsFile>> calculateWorkspaceState(final FilePath workspace) throws IOException,
InterruptedException {
Map<CvsRepository, List<CvsFile>> workspaceState = new HashMap<CvsRepository, List<CvsFile>>();
for (CvsRepository repository : getRepositories()) {
List<CvsFile> cvsFiles = new ArrayList<CvsFile>();
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
for (CvsModule module : item.getModules()) {
cvsFiles.addAll(getCvsFiles(workspace, module, flatten));
}
}
workspaceState.put(repository, cvsFiles);
}
return workspaceState;
}
private List<CvsFile> getCvsFiles(final FilePath workspace, final CvsModule module, final boolean flatten)
throws IOException, InterruptedException {
FilePath targetWorkspace;
if (flatten) {
targetWorkspace = workspace;
} else {
targetWorkspace = workspace.child(module.getCheckoutName());
}
return targetWorkspace.act(new FileCallable<List<CvsFile>>() {
private static final long serialVersionUID = 8158155902777163137L;
@Override
public List<CvsFile> invoke(final File moduleLocation, final VirtualChannel channel) throws IOException,
InterruptedException {
/*
* we use the remote name because we're actually wanting the
* workspace represented as it would be in CVS. This then allows
* us to do a comparison against the file list returned by the
* rlog command (which wouldn't be possible if we use the local
* module name on a module that had been checked out as an alias
*/
return buildFileList(moduleLocation, module.getRemoteName());
}
public List<CvsFile> buildFileList(final File moduleLocation, final String prefix) throws IOException {
AdminHandler adminHandler = new StandardAdminHandler();
List<CvsFile> fileList = new ArrayList<CvsFile>();
if (moduleLocation.isFile()) {
Entry entry = adminHandler.getEntry(moduleLocation);
if (entry != null) {
fileList.add(new CvsFile(entry.getName(), entry.getRevision()));
}
} else {
for (File file : adminHandler.getAllFiles(moduleLocation)) {
if (file.isFile()) {
Entry entry = adminHandler.getEntry(file);
CvsFile currentFile = new CvsFile(prefix + "/" + entry.getName(), entry.getRevision());
fileList.add(currentFile);
}
}
// JENKINS-12807: we get a NPE here which shouldn't be possible given we know
// the file we're getting children of is a directory, but we'll do a null check
// for safety
File[] directoryFiles = moduleLocation.listFiles();
if (directoryFiles != null) {
for (File file : directoryFiles) {
if (file.isDirectory()) {
fileList.addAll(buildFileList(file, prefix + "/" + file.getName()));
}
}
}
}
return fileList;
}
});
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Extension
public static class DescriptorImpl extends SCMDescriptor<CVSSCM> implements ModelObject {
// start legacy fields
private transient String cvsPassFile;
@SuppressWarnings("unused")
private transient String cvsExe;
private transient boolean noCompression;
private class RepositoryBrowser {
@SuppressWarnings("unused")
transient String diffURL;
@SuppressWarnings("unused")
transient String browseURL;
}
@SuppressWarnings("unused")
private transient Map<String, RepositoryBrowser> browsers;
// end legacy fields
/**
* CVS compression level if individual repositories don't specifically
* set it.
*/
private int compressionLevel = 3;
private String privateKeyLocation = System.getProperty("user.home") + "/.ssh/id_rsa";
private Secret privateKeyPassword = null;
private String knownHostsLocation = System.getProperty("user.home") + "/.ssh/known_hosts";
private Map<String, Secret> passwords = new HashMap<String, Secret>();
public DescriptorImpl() {
super(CVSRepositoryBrowser.class);
load();
}
@Override
public String getDisplayName() {
return "CVS";
}
@Override
public SCM newInstance(final StaplerRequest req, final JSONObject formData) throws FormException {
CVSSCM scm = req.bindJSON(CVSSCM.class, formData);
scm.repositoryBrowser = RepositoryBrowsers.createInstance(CVSRepositoryBrowser.class, req, formData,
"browser");
return scm;
}
@Exported
public String getPrivateKeyLocation() {
return privateKeyLocation;
}
public void setPrivateKeyLocation(String privateKeyLocation) {
this.privateKeyLocation = privateKeyLocation;
}
@Exported
public Secret getPrivateKeyPassword() {
return privateKeyPassword;
}
public void setPrivateKeyPassword(String privateKeyPassword) {
this.privateKeyPassword = Secret.fromString(privateKeyPassword);
}
@Exported
public String getKnownHostsLocation() {
return knownHostsLocation;
}
public void setKnownHostsLocation(String knownHostsLocation) {
this.knownHostsLocation = knownHostsLocation;
}
public int getCompressionLevel() {
return compressionLevel;
}
public void setCompressionLevel(final int compressionLevel) {
this.compressionLevel = compressionLevel;
}
@Override
public void load() {
super.load();
// used to move to the new data structure
if (noCompression) {
compressionLevel = 0;
}
}
@Override
public boolean configure(final StaplerRequest req, final JSONObject o) {
String compressionLevel = fixEmptyAndTrim(o.getString("cvsCompression"));
try {
this.compressionLevel = Integer.parseInt(compressionLevel);
} catch (final NumberFormatException ex) {
this.compressionLevel = 0;
}
final String knownHostsLocation = fixEmptyAndTrim(o.getString("knownHostsLocation"));
if (knownHostsLocation == null) {
this.knownHostsLocation = System.getProperty("user.home") + "/.ssh/known_hosts";
} else {
this.knownHostsLocation = knownHostsLocation;
}
final String privateKeyLocation = fixEmptyAndTrim(o.getString("privateKeyLocation"));
if (privateKeyLocation == null) {
this.privateKeyLocation = System.getProperty("user.home") + "/.ssh/id_rsa";
} else {
this.privateKeyLocation = privateKeyLocation;
}
privateKeyPassword = Secret.fromString(fixEmptyAndTrim(o.getString("privateKeyPassword")));
save();
return true;
}
@Override
public boolean isBrowserReusable(final CVSSCM x, final CVSSCM y) {
return false;
}
/**
* Returns all {@code CVSROOT} strings used in the current Jenkins
* installation.
*/
public Set<String> getAllCvsRoots() {
Set<String> r = new TreeSet<String>();
for (AbstractProject<?, ?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
SCM scm = p.getScm();
if (scm instanceof CVSSCM) {
CVSSCM cvsscm = (CVSSCM) scm;
for (CvsRepository repository : cvsscm.getRepositories()) {
r.add(repository.getCvsRoot());
}
}
}
return r;
}
@Deprecated
public String getCvsPassFile() {
return cvsPassFile;
}
//
// web methods
//
}
/**
* Action for a build that performs the tagging.
*
* @deprecated we now use CvsTagAction but have to keep this class around
* for old builds that have a serialized version of this class
* and use the old archive method of tagging a build
*/
@Deprecated
public final class TagAction extends AbstractScmTagAction implements Describable<TagAction> {
private String tagName;
public TagAction(final AbstractBuild<?, ?> build) {
super(build);
}
@Override
public String getIconFileName() {
return null;
}
@Override
public String getDisplayName() {
return null;
}
@Override
public Descriptor<TagAction> getDescriptor() {
return null;
}
@Override
public boolean isTagged() {
return false;
}
/**
* Convert the old TagAction structure into the new (legacy) structure
*
* @return an instance of LegacyTagAction
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws SecurityException
* @throws IllegalArgumentException
*/
public Object readResolve() throws IllegalArgumentException, SecurityException, IllegalAccessException, NoSuchFieldException {
LegacyTagAction legacyTagAction = new LegacyTagAction(super.build, CVSSCM.this);
Field tagNameField = legacyTagAction.getClass().getDeclaredField("tagName");
tagNameField.setAccessible(true);
tagNameField.set(legacyTagAction, tagName);
return legacyTagAction;
}
}
}
| false | true | public boolean checkout(final AbstractBuild<?, ?> build, final Launcher launcher, final FilePath workspace,
final BuildListener listener, final File changelogFile) throws IOException, InterruptedException {
if (!canUseUpdate) {
workspace.deleteContents();
}
final EnvVars envVars = build.getEnvironment(listener);
final String dateStamp;
final Date buildDate = new Date();
synchronized (DATE_FORMATTER) {
dateStamp = DATE_FORMATTER.format(buildDate);
}
for (CvsRepository repository : repositories) {
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
for (CvsModule cvsModule : item.getModules()) {
final FilePath targetWorkspace = flatten ? workspace.getParent() : workspace;
final String moduleName= flatten ? workspace.getName() : cvsModule.getCheckoutName();
final FilePath module = targetWorkspace.child(moduleName);
boolean updateFailed = false;
boolean update = false;
if (flatten) {
if (workspace.child("CVS/Entries").exists()) {
update = true;
}
} else {
if (canUseUpdate && module.exists()) {
update = true;
}
}
CvsRepositoryLocation repositoryLocation = item.getLocation();
CvsRepositoryLocationType locationType = repositoryLocation.getLocationType();
String locationName = repositoryLocation.getLocationName();
String expandedLocationName = envVars.expand(locationName);
// we're doing an update
if (update) {
// we're doing a CVS update
UpdateCommand updateCommand = new UpdateCommand();
// force it to recurse into directories
updateCommand.setBuildDirectories(true);
updateCommand.setRecursive(true);
// set directory pruning
updateCommand.setPruneDirectories(isPruneEmptyDirectories());
// point to head, branch or tag
if (locationType == CvsRepositoryLocationType.BRANCH) {
updateCommand.setUpdateByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
updateCommand.setUseHeadIfNotFound(true);
} else {
updateCommand.setUpdateByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
updateCommand.setUpdateByRevision(expandedLocationName);
updateCommand.setUseHeadIfNotFound(repositoryLocation.isUseHeadIfNotFound());
} else {
updateCommand.setUpdateByRevision(CvsRepositoryLocationType.HEAD.getName().toUpperCase());
updateCommand.setUpdateByDate(dateStamp);
}
if (!perform(updateCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
if (cleanOnFailedUpdate) {
updateFailed = true;
} else {
return false;
}
}
}
// we're doing a checkout
if (!update || (updateFailed && cleanOnFailedUpdate)) {
if (!module.exists()) {
module.mkdirs();
}
if (updateFailed) {
listener.getLogger().println("Update failed. Cleaning workspace and performing full checkout");
workspace.deleteContents();
}
// we're doing a CVS checkout
CheckoutCommand checkoutCommand = new CheckoutCommand();
// point to branch or tag if specified
if (locationType == CvsRepositoryLocationType.BRANCH) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
} else {
checkoutCommand.setCheckoutByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
}
} else if (locationType == CvsRepositoryLocationType.HEAD) {
checkoutCommand.setCheckoutByDate(dateStamp);
}
// set directory pruning
checkoutCommand.setPruneDirectories(isPruneEmptyDirectories());
// set where we're checking out to
checkoutCommand.setCheckoutDirectory(moduleName);
// and specify which module to load
checkoutCommand.setModule(cvsModule.getRemoteName());
if (!perform(checkoutCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
return false;
}
}
}
}
}
// build change log
final AbstractBuild<?, ?> lastCompleteBuild = build.getPreviousBuiltBuild();
if (lastCompleteBuild != null && !isSkipChangeLog()) {
final List<CVSChangeLog> changes = new ArrayList<CVSChangeLog>();
for (CvsRepository location : repositories) {
changes.addAll(calculateChangeLog(lastCompleteBuild.getTime(), build.getTime(), location, launcher,
workspace, listener, build.getEnvironment(listener)));
}
CvsChangeLogHelper.getInstance().toFile(changes, changelogFile);
}
// add the current workspace state as an action
build.getActions().add(new CvsRevisionState(calculateWorkspaceState(workspace)));
// add the tag action to the build
build.getActions().add(new CvsTagAction(build, this));
// remove sticky date tags
workspace.act(new FileCallable<Void>() {
private static final long serialVersionUID = -6867861913158282961L;
@Override
public Void invoke(final File f, final VirtualChannel channel) throws IOException {
AdminHandler adminHandler = new StandardAdminHandler();
for (File file : adminHandler.getAllFiles(f)) {
Entry entry = adminHandler.getEntry(file);
entry.setDate(null);
adminHandler.setEntry(file, entry);
}
return null;
}
});
return true;
}
| public boolean checkout(final AbstractBuild<?, ?> build, final Launcher launcher, final FilePath workspace,
final BuildListener listener, final File changelogFile) throws IOException, InterruptedException {
if (!canUseUpdate) {
workspace.deleteContents();
}
final EnvVars envVars = build.getEnvironment(listener);
final String dateStamp;
final Date buildDate = new Date();
synchronized (DATE_FORMATTER) {
dateStamp = DATE_FORMATTER.format(buildDate);
}
for (CvsRepository repository : repositories) {
for (CvsRepositoryItem item : repository.getRepositoryItems()) {
for (CvsModule cvsModule : item.getModules()) {
final FilePath targetWorkspace = flatten ? workspace.getParent() : workspace;
final String moduleName= flatten ? workspace.getName() : cvsModule.getCheckoutName();
final FilePath module = targetWorkspace.child(moduleName);
boolean updateFailed = false;
boolean update = false;
if (flatten) {
if (workspace.child("CVS/Entries").exists()) {
update = true;
}
} else {
if (canUseUpdate && module.exists()) {
update = true;
}
}
CvsRepositoryLocation repositoryLocation = item.getLocation();
CvsRepositoryLocationType locationType = repositoryLocation.getLocationType();
String locationName = repositoryLocation.getLocationName();
String expandedLocationName = envVars.expand(locationName);
// we're doing an update
if (update) {
// we're doing a CVS update
UpdateCommand updateCommand = new UpdateCommand();
// force it to recurse into directories
updateCommand.setBuildDirectories(true);
updateCommand.setRecursive(true);
// set directory pruning
updateCommand.setPruneDirectories(isPruneEmptyDirectories());
// point to head, branch or tag
if (locationType == CvsRepositoryLocationType.BRANCH) {
updateCommand.setUpdateByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
updateCommand.setUseHeadIfNotFound(true);
updateCommand.setUpdateByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
updateCommand.setUpdateByRevision(expandedLocationName);
updateCommand.setUseHeadIfNotFound(repositoryLocation.isUseHeadIfNotFound());
} else {
updateCommand.setUpdateByRevision(CvsRepositoryLocationType.HEAD.getName().toUpperCase());
updateCommand.setUpdateByDate(dateStamp);
}
if (!perform(updateCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
if (cleanOnFailedUpdate) {
updateFailed = true;
} else {
return false;
}
}
}
// we're doing a checkout
if (!update || (updateFailed && cleanOnFailedUpdate)) {
if (!module.exists()) {
module.mkdirs();
}
if (updateFailed) {
listener.getLogger().println("Update failed. Cleaning workspace and performing full checkout");
workspace.deleteContents();
}
// we're doing a CVS checkout
CheckoutCommand checkoutCommand = new CheckoutCommand();
// point to branch or tag if specified
if (locationType == CvsRepositoryLocationType.BRANCH) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
checkoutCommand.setCheckoutByDate(dateStamp);
}
} else if (locationType == CvsRepositoryLocationType.TAG) {
checkoutCommand.setCheckoutByRevision(expandedLocationName);
if (repositoryLocation.isUseHeadIfNotFound()) {
checkoutCommand.setUseHeadIfNotFound(true);
}
} else if (locationType == CvsRepositoryLocationType.HEAD) {
checkoutCommand.setCheckoutByDate(dateStamp);
}
// set directory pruning
checkoutCommand.setPruneDirectories(isPruneEmptyDirectories());
// set where we're checking out to
checkoutCommand.setCheckoutDirectory(moduleName);
// and specify which module to load
checkoutCommand.setModule(cvsModule.getRemoteName());
if (!perform(checkoutCommand, targetWorkspace, listener, repository, moduleName, envVars)) {
return false;
}
}
}
}
}
// build change log
final AbstractBuild<?, ?> lastCompleteBuild = build.getPreviousBuiltBuild();
if (lastCompleteBuild != null && !isSkipChangeLog()) {
final List<CVSChangeLog> changes = new ArrayList<CVSChangeLog>();
for (CvsRepository location : repositories) {
changes.addAll(calculateChangeLog(lastCompleteBuild.getTime(), build.getTime(), location, launcher,
workspace, listener, build.getEnvironment(listener)));
}
CvsChangeLogHelper.getInstance().toFile(changes, changelogFile);
}
// add the current workspace state as an action
build.getActions().add(new CvsRevisionState(calculateWorkspaceState(workspace)));
// add the tag action to the build
build.getActions().add(new CvsTagAction(build, this));
// remove sticky date tags
workspace.act(new FileCallable<Void>() {
private static final long serialVersionUID = -6867861913158282961L;
@Override
public Void invoke(final File f, final VirtualChannel channel) throws IOException {
AdminHandler adminHandler = new StandardAdminHandler();
for (File file : adminHandler.getAllFiles(f)) {
Entry entry = adminHandler.getEntry(file);
entry.setDate(null);
adminHandler.setEntry(file, entry);
}
return null;
}
});
return true;
}
|
diff --git a/src/main/java/org/got5/tapestry5/jquery/jqplot/components/JqPlotDateZooming.java b/src/main/java/org/got5/tapestry5/jquery/jqplot/components/JqPlotDateZooming.java
index 5652929..280a82d 100644
--- a/src/main/java/org/got5/tapestry5/jquery/jqplot/components/JqPlotDateZooming.java
+++ b/src/main/java/org/got5/tapestry5/jquery/jqplot/components/JqPlotDateZooming.java
@@ -1,130 +1,130 @@
package org.got5.tapestry5.jquery.jqplot.components;
import java.util.Date;
import java.util.List;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
import org.got5.tapestry5.jquery.jqplot.util.DateUtil;
import org.got5.tapestry5.jquery.jqplot.util.StringUtil;
/**
* This graph plots X (Date) and Y with zooming feature explained on this example page http://www.jqplot.com/tests/zooming.php
*/
@Import( library={ "${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.cursor.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.logAxisRenderer.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.logAxisRenderer.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.canvasTextRenderer.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.canvasAxisLabelRenderer.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.canvasAxisTickRenderer.min.js",
"${jquery.jqplot.core.path}/jquery/jqplot/${jquery.jqplot.version}/plugins/jqplot.dateAxisRenderer.min.js"})
public class JqPlotDateZooming extends JqPlot {
@Parameter(name = "xAxisMinDate", required=false)
private Date xAxisMinDate;
@Parameter(name = "xAxisMaxDate", required=false)
private Date xAxisMaxDate;
@Parameter(name = "xAxisTickerInterval", required=false)
private String xAxisTickerInterval;
@Parameter(name = "xAxisLabel", required=false)
private String xAxisLabel;
@Parameter(name = "yAxisLabel", required=false)
private String yAxisLabel;
@Parameter(name = "seriesLabels", required = false, defaultPrefix = BindingConstants.PROP)
private List<String> seriesLabels;
/**
* Invoked to allow subclasses to further configure the parameters passed to this component's javascript
* options. Subclasses may override this method to configure additional features of the jqPlot library.
*
* @param config parameters object
*/
protected void configure(JSONObject config)
{
JSONObject options = new JSONObject();
config.put("options", options);
// data items might have series labels
// user is responsible for setting label for each series. Do not make mistake.
// Size of dataSeries and Size of series lable has to be equal.
if(seriesLabels != null && seriesLabels.size()>0) {
JSONArray series = new JSONArray();
for(String currentLabel: seriesLabels) {
JSONObject labelEntry = new JSONObject();
labelEntry.put("label", new JSONLiteral("'" + currentLabel + "'"));
series.put(labelEntry);
}
options.put("series", series);
options.put("legend", new JSONObject("{ show:true, location: 'nw' }"));
}
JSONObject axes = new JSONObject();
options.put("axes", axes);
JSONObject xaxis = new JSONObject();
axes.put("xaxis", xaxis);
if(StringUtil.isNonEmptyString(xAxisLabel)) {
xaxis.put("label", new JSONLiteral("'"+xAxisLabel.trim()+"'"));
}
xaxis.put("renderer", new JSONLiteral("jQuery.jqplot.DateAxisRenderer"));
if(xAxisMinDate != null) {
xaxis.put("min", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMinDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'" ));
}
if(xAxisMaxDate != null) {
xaxis.put("max", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMaxDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'"));
}
if(xAxisTickerInterval != null && isXAxisTickerIntervalValid(xAxisTickerInterval) ) {
xaxis.put("tickInterval", new JSONLiteral("'" + xAxisTickerInterval + "'"));
}
JSONObject xTickOptions = new JSONObject();
xaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
xTickOptions.put("formatString", new JSONLiteral("'%H:%M:%S'"));
xTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
xTickOptions.put("angle", new JSONLiteral("-90"));
xaxis.put("tickOptions", xTickOptions);
xaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject yaxis = new JSONObject();
axes.put("yaxis", yaxis);
if(StringUtil.isNonEmptyString(yAxisLabel)) {
yaxis.put("label", new JSONLiteral("'"+yAxisLabel.trim()+"'"));
}
JSONObject yTickOptions = new JSONObject();
yaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
- yTickOptions.put("formatString", new JSONLiteral("'%s'"));
+ yTickOptions.put("formatString", new JSONLiteral("'%.2f'"));
yTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
yaxis.put("tickOptions", yTickOptions);
yaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject cursor = new JSONObject();
cursor.put("show", new JSONLiteral("true"));
cursor.put("zoom", new JSONLiteral("true"));
cursor.put("showTooltip", new JSONLiteral("true"));
cursor.put("dblClickReset", new JSONLiteral("true"));
options.put("cursor", cursor);
}
private boolean isXAxisTickerIntervalValid(String xAxisTickerInterval) {
// TODO: implement validation logic
return true;
}
}
| true | true | protected void configure(JSONObject config)
{
JSONObject options = new JSONObject();
config.put("options", options);
// data items might have series labels
// user is responsible for setting label for each series. Do not make mistake.
// Size of dataSeries and Size of series lable has to be equal.
if(seriesLabels != null && seriesLabels.size()>0) {
JSONArray series = new JSONArray();
for(String currentLabel: seriesLabels) {
JSONObject labelEntry = new JSONObject();
labelEntry.put("label", new JSONLiteral("'" + currentLabel + "'"));
series.put(labelEntry);
}
options.put("series", series);
options.put("legend", new JSONObject("{ show:true, location: 'nw' }"));
}
JSONObject axes = new JSONObject();
options.put("axes", axes);
JSONObject xaxis = new JSONObject();
axes.put("xaxis", xaxis);
if(StringUtil.isNonEmptyString(xAxisLabel)) {
xaxis.put("label", new JSONLiteral("'"+xAxisLabel.trim()+"'"));
}
xaxis.put("renderer", new JSONLiteral("jQuery.jqplot.DateAxisRenderer"));
if(xAxisMinDate != null) {
xaxis.put("min", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMinDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'" ));
}
if(xAxisMaxDate != null) {
xaxis.put("max", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMaxDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'"));
}
if(xAxisTickerInterval != null && isXAxisTickerIntervalValid(xAxisTickerInterval) ) {
xaxis.put("tickInterval", new JSONLiteral("'" + xAxisTickerInterval + "'"));
}
JSONObject xTickOptions = new JSONObject();
xaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
xTickOptions.put("formatString", new JSONLiteral("'%H:%M:%S'"));
xTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
xTickOptions.put("angle", new JSONLiteral("-90"));
xaxis.put("tickOptions", xTickOptions);
xaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject yaxis = new JSONObject();
axes.put("yaxis", yaxis);
if(StringUtil.isNonEmptyString(yAxisLabel)) {
yaxis.put("label", new JSONLiteral("'"+yAxisLabel.trim()+"'"));
}
JSONObject yTickOptions = new JSONObject();
yaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
yTickOptions.put("formatString", new JSONLiteral("'%s'"));
yTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
yaxis.put("tickOptions", yTickOptions);
yaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject cursor = new JSONObject();
cursor.put("show", new JSONLiteral("true"));
cursor.put("zoom", new JSONLiteral("true"));
cursor.put("showTooltip", new JSONLiteral("true"));
cursor.put("dblClickReset", new JSONLiteral("true"));
options.put("cursor", cursor);
}
| protected void configure(JSONObject config)
{
JSONObject options = new JSONObject();
config.put("options", options);
// data items might have series labels
// user is responsible for setting label for each series. Do not make mistake.
// Size of dataSeries and Size of series lable has to be equal.
if(seriesLabels != null && seriesLabels.size()>0) {
JSONArray series = new JSONArray();
for(String currentLabel: seriesLabels) {
JSONObject labelEntry = new JSONObject();
labelEntry.put("label", new JSONLiteral("'" + currentLabel + "'"));
series.put(labelEntry);
}
options.put("series", series);
options.put("legend", new JSONObject("{ show:true, location: 'nw' }"));
}
JSONObject axes = new JSONObject();
options.put("axes", axes);
JSONObject xaxis = new JSONObject();
axes.put("xaxis", xaxis);
if(StringUtil.isNonEmptyString(xAxisLabel)) {
xaxis.put("label", new JSONLiteral("'"+xAxisLabel.trim()+"'"));
}
xaxis.put("renderer", new JSONLiteral("jQuery.jqplot.DateAxisRenderer"));
if(xAxisMinDate != null) {
xaxis.put("min", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMinDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'" ));
}
if(xAxisMaxDate != null) {
xaxis.put("max", new JSONLiteral("'" + DateUtil.getTimestamp(xAxisMaxDate, DateUtil.TIMESTAMP_PATTERN_FOR_JSON_MIN_OR_MAX_DATE) + "'"));
}
if(xAxisTickerInterval != null && isXAxisTickerIntervalValid(xAxisTickerInterval) ) {
xaxis.put("tickInterval", new JSONLiteral("'" + xAxisTickerInterval + "'"));
}
JSONObject xTickOptions = new JSONObject();
xaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
xTickOptions.put("formatString", new JSONLiteral("'%H:%M:%S'"));
xTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
xTickOptions.put("angle", new JSONLiteral("-90"));
xaxis.put("tickOptions", xTickOptions);
xaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject yaxis = new JSONObject();
axes.put("yaxis", yaxis);
if(StringUtil.isNonEmptyString(yAxisLabel)) {
yaxis.put("label", new JSONLiteral("'"+yAxisLabel.trim()+"'"));
}
JSONObject yTickOptions = new JSONObject();
yaxis.put("labelRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisLabelRenderer"));
yTickOptions.put("formatString", new JSONLiteral("'%.2f'"));
yTickOptions.put("labelPosition", new JSONLiteral("'middle'"));
yaxis.put("tickOptions", yTickOptions);
yaxis.put("tickRenderer", new JSONLiteral("jQuery.jqplot.CanvasAxisTickRenderer"));
JSONObject cursor = new JSONObject();
cursor.put("show", new JSONLiteral("true"));
cursor.put("zoom", new JSONLiteral("true"));
cursor.put("showTooltip", new JSONLiteral("true"));
cursor.put("dblClickReset", new JSONLiteral("true"));
options.put("cursor", cursor);
}
|
diff --git a/src/java/org/apache/nutch/crawl/Crawl.java b/src/java/org/apache/nutch/crawl/Crawl.java
index e26beb69..26bd582f 100644
--- a/src/java/org/apache/nutch/crawl/Crawl.java
+++ b/src/java/org/apache/nutch/crawl/Crawl.java
@@ -1,127 +1,127 @@
/**
* Copyright 2005 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.crawl;
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.util.logging.*;
import org.apache.nutch.io.*;
import org.apache.nutch.fetcher.Fetcher;
import org.apache.nutch.fs.*;
import org.apache.nutch.util.*;
import org.apache.nutch.mapred.*;
import org.apache.nutch.parse.ParseSegment;
import org.apache.nutch.indexer.DeleteDuplicates;
import org.apache.nutch.indexer.IndexMerger;
import org.apache.nutch.indexer.Indexer;
public class Crawl {
public static final Logger LOG =
LogFormatter.getLogger("org.apache.nutch.crawl.Crawl");
private static String getDate() {
return new SimpleDateFormat("yyyyMMddHHmmss").format
(new Date(System.currentTimeMillis()));
}
static {
NutchConf.get().addConfResource("crawl-tool.xml");
}
/* Perform complete crawling and indexing given a set of root urls. */
public static void main(String args[]) throws Exception {
if (args.length < 1) {
System.out.println
("Usage: Crawl <urlDir> [-dir d] [-threads n] [-depth i] [-topN N]");
return;
}
JobConf conf = new JobConf(NutchConf.get());
//conf.addConfResource("crawl-tool.xml");
File rootUrlDir = null;
File dir = new File("crawl-" + getDate());
int threads = conf.getInt("fetcher.threads.fetch", 10);
int depth = 5;
int topN = Integer.MAX_VALUE;
for (int i = 0; i < args.length; i++) {
if ("-dir".equals(args[i])) {
dir = new File(args[i+1]);
i++;
} else if ("-threads".equals(args[i])) {
threads = Integer.parseInt(args[i+1]);
i++;
} else if ("-depth".equals(args[i])) {
depth = Integer.parseInt(args[i+1]);
i++;
} else if ("-topN".equals(args[i])) {
topN = Integer.parseInt(args[i+1]);
i++;
} else if (args[i] != null) {
rootUrlDir = new File(args[i]);
}
}
NutchFileSystem fs = NutchFileSystem.get(conf);
if (fs.exists(dir)) {
throw new RuntimeException(dir + " already exists.");
}
LOG.info("crawl started in: " + dir);
LOG.info("rootUrlDir = " + rootUrlDir);
LOG.info("threads = " + threads);
LOG.info("depth = " + depth);
if (topN != Integer.MAX_VALUE)
LOG.info("topN = " + topN);
File crawlDb = new File(dir + "/crawldb");
File linkDb = new File(dir + "/linkdb");
File segments = new File(dir + "/segments");
File indexes = new File(dir + "/indexes");
File index = new File(dir + "/index");
File tmpDir = conf.getLocalFile("crawl", getDate());
// initialize crawlDb
new Injector(conf).inject(crawlDb, rootUrlDir);
for (int i = 0; i < depth; i++) { // generate new segment
File segment =
new Generator(conf).generate(crawlDb, segments, -1,
topN, System.currentTimeMillis());
- new Fetcher(conf).fetch(segment, threads); // fetch it
+ new Fetcher(conf).fetch(segment, threads, Fetcher.isParsing(conf)); // fetch it
if (!Fetcher.isParsing(conf)) {
new ParseSegment(conf).parse(segment); // parse it, if needed
}
new CrawlDb(conf).update(crawlDb, segment); // update crawldb
}
new LinkDb(conf).invert(linkDb, segments); // invert links
// index, dedup & merge
new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));
new DeleteDuplicates(conf).dedup(new File[] { indexes });
new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir).merge();
LOG.info("crawl finished: " + dir);
}
}
| true | true | public static void main(String args[]) throws Exception {
if (args.length < 1) {
System.out.println
("Usage: Crawl <urlDir> [-dir d] [-threads n] [-depth i] [-topN N]");
return;
}
JobConf conf = new JobConf(NutchConf.get());
//conf.addConfResource("crawl-tool.xml");
File rootUrlDir = null;
File dir = new File("crawl-" + getDate());
int threads = conf.getInt("fetcher.threads.fetch", 10);
int depth = 5;
int topN = Integer.MAX_VALUE;
for (int i = 0; i < args.length; i++) {
if ("-dir".equals(args[i])) {
dir = new File(args[i+1]);
i++;
} else if ("-threads".equals(args[i])) {
threads = Integer.parseInt(args[i+1]);
i++;
} else if ("-depth".equals(args[i])) {
depth = Integer.parseInt(args[i+1]);
i++;
} else if ("-topN".equals(args[i])) {
topN = Integer.parseInt(args[i+1]);
i++;
} else if (args[i] != null) {
rootUrlDir = new File(args[i]);
}
}
NutchFileSystem fs = NutchFileSystem.get(conf);
if (fs.exists(dir)) {
throw new RuntimeException(dir + " already exists.");
}
LOG.info("crawl started in: " + dir);
LOG.info("rootUrlDir = " + rootUrlDir);
LOG.info("threads = " + threads);
LOG.info("depth = " + depth);
if (topN != Integer.MAX_VALUE)
LOG.info("topN = " + topN);
File crawlDb = new File(dir + "/crawldb");
File linkDb = new File(dir + "/linkdb");
File segments = new File(dir + "/segments");
File indexes = new File(dir + "/indexes");
File index = new File(dir + "/index");
File tmpDir = conf.getLocalFile("crawl", getDate());
// initialize crawlDb
new Injector(conf).inject(crawlDb, rootUrlDir);
for (int i = 0; i < depth; i++) { // generate new segment
File segment =
new Generator(conf).generate(crawlDb, segments, -1,
topN, System.currentTimeMillis());
new Fetcher(conf).fetch(segment, threads); // fetch it
if (!Fetcher.isParsing(conf)) {
new ParseSegment(conf).parse(segment); // parse it, if needed
}
new CrawlDb(conf).update(crawlDb, segment); // update crawldb
}
new LinkDb(conf).invert(linkDb, segments); // invert links
// index, dedup & merge
new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));
new DeleteDuplicates(conf).dedup(new File[] { indexes });
new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir).merge();
LOG.info("crawl finished: " + dir);
}
| public static void main(String args[]) throws Exception {
if (args.length < 1) {
System.out.println
("Usage: Crawl <urlDir> [-dir d] [-threads n] [-depth i] [-topN N]");
return;
}
JobConf conf = new JobConf(NutchConf.get());
//conf.addConfResource("crawl-tool.xml");
File rootUrlDir = null;
File dir = new File("crawl-" + getDate());
int threads = conf.getInt("fetcher.threads.fetch", 10);
int depth = 5;
int topN = Integer.MAX_VALUE;
for (int i = 0; i < args.length; i++) {
if ("-dir".equals(args[i])) {
dir = new File(args[i+1]);
i++;
} else if ("-threads".equals(args[i])) {
threads = Integer.parseInt(args[i+1]);
i++;
} else if ("-depth".equals(args[i])) {
depth = Integer.parseInt(args[i+1]);
i++;
} else if ("-topN".equals(args[i])) {
topN = Integer.parseInt(args[i+1]);
i++;
} else if (args[i] != null) {
rootUrlDir = new File(args[i]);
}
}
NutchFileSystem fs = NutchFileSystem.get(conf);
if (fs.exists(dir)) {
throw new RuntimeException(dir + " already exists.");
}
LOG.info("crawl started in: " + dir);
LOG.info("rootUrlDir = " + rootUrlDir);
LOG.info("threads = " + threads);
LOG.info("depth = " + depth);
if (topN != Integer.MAX_VALUE)
LOG.info("topN = " + topN);
File crawlDb = new File(dir + "/crawldb");
File linkDb = new File(dir + "/linkdb");
File segments = new File(dir + "/segments");
File indexes = new File(dir + "/indexes");
File index = new File(dir + "/index");
File tmpDir = conf.getLocalFile("crawl", getDate());
// initialize crawlDb
new Injector(conf).inject(crawlDb, rootUrlDir);
for (int i = 0; i < depth; i++) { // generate new segment
File segment =
new Generator(conf).generate(crawlDb, segments, -1,
topN, System.currentTimeMillis());
new Fetcher(conf).fetch(segment, threads, Fetcher.isParsing(conf)); // fetch it
if (!Fetcher.isParsing(conf)) {
new ParseSegment(conf).parse(segment); // parse it, if needed
}
new CrawlDb(conf).update(crawlDb, segment); // update crawldb
}
new LinkDb(conf).invert(linkDb, segments); // invert links
// index, dedup & merge
new Indexer(conf).index(indexes, crawlDb, linkDb, fs.listFiles(segments));
new DeleteDuplicates(conf).dedup(new File[] { indexes });
new IndexMerger(fs, fs.listFiles(indexes), index, tmpDir).merge();
LOG.info("crawl finished: " + dir);
}
|
diff --git a/src/com/edinarobotics/zed/Controls.java b/src/com/edinarobotics/zed/Controls.java
index a3fc728..f1ac4ff 100644
--- a/src/com/edinarobotics/zed/Controls.java
+++ b/src/com/edinarobotics/zed/Controls.java
@@ -1,88 +1,87 @@
package com.edinarobotics.zed;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.zed.commands.*;
import com.edinarobotics.zed.subsystems.Auger;
import com.edinarobotics.zed.subsystems.Collector;
import com.edinarobotics.zed.subsystems.Conveyor;
import com.edinarobotics.zed.subsystems.Lifter;
import com.edinarobotics.zed.subsystems.Shooter;
/**
* Controls handles creating the {@link Gamepad} objects
* used to control the robot as well as binding the proper Commands
* to button actions.
*/
public class Controls {
private static Controls instance;
private static final double ONE_JOYSTICK_MAGNITUDE = 1;
public final Gamepad gamepad1;
public final Gamepad gamepad2;
private Controls(){
gamepad1 = new Gamepad(1);
//Drivetrain Direction Toggle
gamepad1.DIAMOND_LEFT.whenPressed(new ToggleDrivetrainDirectionCommand());
//Conveyor
gamepad1.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_IN));
gamepad1.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad1.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_OUT));
gamepad1.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Collector
gamepad1.RIGHT_TRIGGER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_IN));
gamepad1.RIGHT_TRIGGER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.RIGHT_BUMPER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_OUT));
gamepad1.RIGHT_BUMPER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.DIAMOND_UP.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_UP));
gamepad1.DIAMOND_UP.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
gamepad1.DIAMOND_DOWN.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_DOWN));
gamepad1.DIAMOND_DOWN.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
- //One-Joystick Strafe
- gamepad1.DPAD_UP.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 0, 0));
- gamepad1.DPAD_UP.whenReleased(new SetDrivetrainCommand(0, 0, 0));
- gamepad1.DPAD_DOWN.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 180, 0));
- gamepad1.DPAD_DOWN.whenReleased(new SetDrivetrainCommand(0, 0, 0));
- gamepad1.DPAD_LEFT.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, -90, 0));
- gamepad1.DPAD_LEFT.whenReleased(new SetDrivetrainCommand(0, 0, 0));
- gamepad1.DPAD_RIGHT.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 90, 0));
- gamepad1.DPAD_RIGHT.whenReleased(new SetDrivetrainCommand(0, 0, 0));
+ //Lifter
+ gamepad1.DPAD_UP.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_UP));
+ gamepad1.DPAD_UP.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
+ gamepad1.DPAD_DOWN.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_DOWN));
+ gamepad1.DPAD_DOWN.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad2 = new Gamepad(2);
//Conveyor
gamepad2.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_IN));
gamepad2.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad2.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_OUT));
gamepad2.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Shooter
gamepad2.RIGHT_TRIGGER.whenPressed(new SetShooterCommand(Shooter.SHOOTER_ON));
gamepad2.RIGHT_TRIGGER.whenReleased(new SetShooterCommand(Shooter.SHOOTER_OFF));
//Augers
gamepad2.RIGHT_BUMPER.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_DOWN));
gamepad2.MIDDLE_RIGHT.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_UP));
gamepad2.MIDDLE_LEFT.whenPressed(new SetAugerCommand(Auger.AugerDirection.AUGER_STOP));
//Vision Tracking
gamepad2.DIAMOND_UP.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.HIGH_GOAL));
- gamepad2.DIAMOND_DOWN.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.MIDDLE_GOAL));
+ gamepad2.DIAMOND_RIGHT.whileHeld(new FixedPointVisionTrackingCommand(FixedPointVisionTrackingCommand.PYRAMID_BACK_RIGHT_X,
+ FixedPointVisionTrackingCommand.PYRAMID_BACK_RIGHT_Y, VisionTrackingCommand.HIGH_GOAL));
gamepad2.DIAMOND_LEFT.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.ANY_GOAL));
- gamepad2.DIAMOND_RIGHT.whileHeld(new FixedPointVisionTrackingCommand(0.0273556, -0.29411, VisionTrackingCommand.HIGH_GOAL));
+ gamepad2.DIAMOND_DOWN.whileHeld(new FixedPointVisionTrackingCommand(FixedPointVisionTrackingCommand.PYRAMID_BACK_MIDDLE_X,
+ FixedPointVisionTrackingCommand.PYRAMID_BACK_MIDDLE_Y, VisionTrackingCommand.HIGH_GOAL));
+ gamepad2.LEFT_JOYSTICK_BUTTON.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.MIDDLE_GOAL));
//Lifter
gamepad2.DPAD_UP.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_UP));
gamepad2.DPAD_UP.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad2.DPAD_DOWN.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_DOWN));
gamepad2.DPAD_DOWN.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
}
/**
* Returns the proper instance of Controls.
* This method creates a new Controls object the first time it is called
* and returns that object for each subsequent call.
* @return The current instance of Controls.
*/
public static Controls getInstance(){
if(instance == null){
instance = new Controls();
}
return instance;
}
}
| false | true | private Controls(){
gamepad1 = new Gamepad(1);
//Drivetrain Direction Toggle
gamepad1.DIAMOND_LEFT.whenPressed(new ToggleDrivetrainDirectionCommand());
//Conveyor
gamepad1.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_IN));
gamepad1.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad1.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_OUT));
gamepad1.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Collector
gamepad1.RIGHT_TRIGGER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_IN));
gamepad1.RIGHT_TRIGGER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.RIGHT_BUMPER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_OUT));
gamepad1.RIGHT_BUMPER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.DIAMOND_UP.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_UP));
gamepad1.DIAMOND_UP.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
gamepad1.DIAMOND_DOWN.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_DOWN));
gamepad1.DIAMOND_DOWN.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
//One-Joystick Strafe
gamepad1.DPAD_UP.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 0, 0));
gamepad1.DPAD_UP.whenReleased(new SetDrivetrainCommand(0, 0, 0));
gamepad1.DPAD_DOWN.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 180, 0));
gamepad1.DPAD_DOWN.whenReleased(new SetDrivetrainCommand(0, 0, 0));
gamepad1.DPAD_LEFT.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, -90, 0));
gamepad1.DPAD_LEFT.whenReleased(new SetDrivetrainCommand(0, 0, 0));
gamepad1.DPAD_RIGHT.whileHeld(new SetDrivetrainCommand(ONE_JOYSTICK_MAGNITUDE, 90, 0));
gamepad1.DPAD_RIGHT.whenReleased(new SetDrivetrainCommand(0, 0, 0));
gamepad2 = new Gamepad(2);
//Conveyor
gamepad2.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_IN));
gamepad2.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad2.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_OUT));
gamepad2.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Shooter
gamepad2.RIGHT_TRIGGER.whenPressed(new SetShooterCommand(Shooter.SHOOTER_ON));
gamepad2.RIGHT_TRIGGER.whenReleased(new SetShooterCommand(Shooter.SHOOTER_OFF));
//Augers
gamepad2.RIGHT_BUMPER.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_DOWN));
gamepad2.MIDDLE_RIGHT.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_UP));
gamepad2.MIDDLE_LEFT.whenPressed(new SetAugerCommand(Auger.AugerDirection.AUGER_STOP));
//Vision Tracking
gamepad2.DIAMOND_UP.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.HIGH_GOAL));
gamepad2.DIAMOND_DOWN.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.MIDDLE_GOAL));
gamepad2.DIAMOND_LEFT.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.ANY_GOAL));
gamepad2.DIAMOND_RIGHT.whileHeld(new FixedPointVisionTrackingCommand(0.0273556, -0.29411, VisionTrackingCommand.HIGH_GOAL));
//Lifter
gamepad2.DPAD_UP.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_UP));
gamepad2.DPAD_UP.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad2.DPAD_DOWN.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_DOWN));
gamepad2.DPAD_DOWN.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
}
| private Controls(){
gamepad1 = new Gamepad(1);
//Drivetrain Direction Toggle
gamepad1.DIAMOND_LEFT.whenPressed(new ToggleDrivetrainDirectionCommand());
//Conveyor
gamepad1.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_IN));
gamepad1.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad1.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_COLLECT_OUT));
gamepad1.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Collector
gamepad1.RIGHT_TRIGGER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_IN));
gamepad1.RIGHT_TRIGGER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.RIGHT_BUMPER.whenPressed(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_OUT));
gamepad1.RIGHT_BUMPER.whenReleased(new SetCollectorCommand(Collector.CollectorDirection.COLLECTOR_STOP));
gamepad1.DIAMOND_UP.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_UP));
gamepad1.DIAMOND_UP.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
gamepad1.DIAMOND_DOWN.whenPressed(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_DOWN));
gamepad1.DIAMOND_DOWN.whenReleased(new SetCollectorCommand(Collector.CollectorLiftDirection.COLLECTOR_LIFT_STOP));
//Lifter
gamepad1.DPAD_UP.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_UP));
gamepad1.DPAD_UP.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad1.DPAD_DOWN.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_DOWN));
gamepad1.DPAD_DOWN.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad2 = new Gamepad(2);
//Conveyor
gamepad2.LEFT_TRIGGER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_IN));
gamepad2.LEFT_TRIGGER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
gamepad2.LEFT_BUMPER.whenPressed(new SetConveyorCommand(Conveyor.CONVEYOR_SHOOT_OUT));
gamepad2.LEFT_BUMPER.whenReleased(new SetConveyorCommand(Conveyor.CONVEYOR_STOP));
//Shooter
gamepad2.RIGHT_TRIGGER.whenPressed(new SetShooterCommand(Shooter.SHOOTER_ON));
gamepad2.RIGHT_TRIGGER.whenReleased(new SetShooterCommand(Shooter.SHOOTER_OFF));
//Augers
gamepad2.RIGHT_BUMPER.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_DOWN));
gamepad2.MIDDLE_RIGHT.whenPressed(new AugerRotateCommand(Auger.AugerDirection.AUGER_UP));
gamepad2.MIDDLE_LEFT.whenPressed(new SetAugerCommand(Auger.AugerDirection.AUGER_STOP));
//Vision Tracking
gamepad2.DIAMOND_UP.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.HIGH_GOAL));
gamepad2.DIAMOND_RIGHT.whileHeld(new FixedPointVisionTrackingCommand(FixedPointVisionTrackingCommand.PYRAMID_BACK_RIGHT_X,
FixedPointVisionTrackingCommand.PYRAMID_BACK_RIGHT_Y, VisionTrackingCommand.HIGH_GOAL));
gamepad2.DIAMOND_LEFT.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.ANY_GOAL));
gamepad2.DIAMOND_DOWN.whileHeld(new FixedPointVisionTrackingCommand(FixedPointVisionTrackingCommand.PYRAMID_BACK_MIDDLE_X,
FixedPointVisionTrackingCommand.PYRAMID_BACK_MIDDLE_Y, VisionTrackingCommand.HIGH_GOAL));
gamepad2.LEFT_JOYSTICK_BUTTON.whileHeld(new VisionTrackingCommand(VisionTrackingCommand.MIDDLE_GOAL));
//Lifter
gamepad2.DPAD_UP.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_UP));
gamepad2.DPAD_UP.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
gamepad2.DPAD_DOWN.whenPressed(new SetLifterCommand(Lifter.LifterDirection.LIFTER_DOWN));
gamepad2.DPAD_DOWN.whenReleased(new SetLifterCommand(Lifter.LifterDirection.LIFTER_STOP));
}
|
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
index 52ef6d50..3db64fe8 100644
--- a/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
+++ b/cli/src/main/java/com/vmware/bdd/cli/commands/ClusterCommands.java
@@ -1,1582 +1,1582 @@
/*****************************************************************************
* Copyright (c) 2012-2013 VMware, 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.vmware.bdd.cli.commands;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import jline.ConsoleReader;
import org.apache.hadoop.conf.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.impala.hive.HiveCommands;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;
import com.vmware.bdd.apitypes.ClusterCreate;
import com.vmware.bdd.apitypes.ClusterRead;
import com.vmware.bdd.apitypes.ClusterRead.ClusterStatus;
import com.vmware.bdd.apitypes.ClusterType;
import com.vmware.bdd.apitypes.DistroRead;
import com.vmware.bdd.apitypes.ElasticityRequestBody;
import com.vmware.bdd.apitypes.ElasticityRequestBody.ElasticityMode;
import com.vmware.bdd.apitypes.FixDiskRequestBody;
import com.vmware.bdd.apitypes.NetConfigInfo.NetTrafficType;
import com.vmware.bdd.apitypes.NetworkRead;
import com.vmware.bdd.apitypes.NodeGroupCreate;
import com.vmware.bdd.apitypes.NodeGroupRead;
import com.vmware.bdd.apitypes.NodeRead;
import com.vmware.bdd.apitypes.Priority;
import com.vmware.bdd.apitypes.ResourceScale;
import com.vmware.bdd.apitypes.TaskRead;
import com.vmware.bdd.apitypes.TaskRead.NodeStatus;
import com.vmware.bdd.apitypes.TopologyType;
import com.vmware.bdd.cli.rest.CliRestException;
import com.vmware.bdd.cli.rest.ClusterRestClient;
import com.vmware.bdd.cli.rest.DistroRestClient;
import com.vmware.bdd.cli.rest.NetworkRestClient;
import com.vmware.bdd.spectypes.HadoopRole;
import com.vmware.bdd.utils.AppConfigValidationUtils;
import com.vmware.bdd.utils.AppConfigValidationUtils.ValidationType;
import com.vmware.bdd.utils.ValidateResult;
@Component
public class ClusterCommands implements CommandMarker {
@Autowired
private DistroRestClient distroRestClient;
@Autowired
private NetworkRestClient networkRestClient;
@Autowired
private ClusterRestClient restClient;
@Autowired
private Configuration hadoopConfiguration;
@Autowired
private HiveCommands hiveCommands;
private String hiveServerUrl;
private String targetClusterName;
@CliAvailabilityIndicator({ "cluster help" })
public boolean isCommandAvailable() {
return true;
}
@CliCommand(value = "cluster create", help = "Create a hadoop cluster")
public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type,
@CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name used for management") final String networkName,
@CliOption(key = { "hdfsNetworkName" }, mandatory = false, help = "Network Name for HDFS traffic.") final String hdfsNetworkName,
@CliOption(key = { "mapredNetworkName" }, mandatory = false, help = "Network Name for MapReduce traffic") final String mapredNetworkName,
@CliOption(key = { "topology" }, mandatory = false, help = "You must specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes,
@CliOption(key = { "password" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Answer 'yes' to set password for all VMs in this cluster.") final boolean setClusterPassword) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
} else if (name.indexOf(" ") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_BLANK_SPACE);
return;
}
// process resume
if (resume && setClusterPassword) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.RESUME_DONOT_NEED_SET_PASSWORD);
return;
} else if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (setClusterPassword) {
String password = getPassword();
//user would like to set password, but failed to enter
//a valid one, quit cluster create
if (password == null) {
return;
} else {
clusterCreate.setPassword(password);
}
}
if (type != null) {
ClusterType clusterType = ClusterType.getByDescription(type);
if (clusterType == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "type=" + type);
return;
}
clusterCreate.setType(clusterType);
} else if (specFilePath == null) {
// create Hadoop (HDFS + MapReduce) cluster as default
clusterCreate.setType(ClusterType.HDFS_MAPRED);
}
if (topology != null) {
try {
clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology));
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "topologyType=" + topology);
return;
}
} else {
clusterCreate.setTopologyPolicy(TopologyType.NONE);
}
try {
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
} else {
String defaultDistroName =
clusterCreate.getDefaultDistroName(distroRestClient.getAll());
if (CommandsUtils.isBlank(defaultDistroName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM__NO_DEFAULT_DISTRO);
return;
} else {
clusterCreate.setDistro(defaultDistroName);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro());
clusterCreate.setDistroVendor(distroRead.getVendor());
clusterCreate.setDistroVersion(distroRead.getVersion());
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> failedMsgList = new ArrayList<String>();
List<String> warningMsgList = new ArrayList<String>();
Set<String> allNetworkNames = new HashSet<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setSpecFile(true);
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation,
warningMsgList);
clusterCreate.validateNodeGroupNames();
if (!validateHAInfo(clusterCreate.getNodeGroups())) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
allNetworkNames = getAllNetworkNames();
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
if (allNetworkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CANNOT_FIND_NETWORK);
return;
}
Map<NetTrafficType, List<String>> networkConfig = new HashMap<NetTrafficType, List<String>>();
if (networkName == null) {
if (allNetworkNames.size() == 1) {
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).addAll(allNetworkNames);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
} else {
if (!allNetworkNames.contains(networkName)
|| (hdfsNetworkName != null && !allNetworkNames.contains(hdfsNetworkName))
|| (mapredNetworkName != null && !allNetworkNames.contains(mapredNetworkName))) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + allNetworkNames.toString());
return;
}
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).add(networkName);
if (hdfsNetworkName != null) {
networkConfig.put(NetTrafficType.HDFS_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.HDFS_NETWORK).add(hdfsNetworkName);
}
if (mapredNetworkName != null) {
networkConfig.put(NetTrafficType.MAPRED_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MAPRED_NETWORK).add(mapredNetworkName);
}
}
notifyNetsUsage(networkConfig, warningMsgList);
clusterCreate.setNetworkConfig(networkConfig);
clusterCreate.validateCDHVersion(warningMsgList);
// Validate that the specified file is correct json format and proper
// value.
if (specFilePath != null) {
List<String> distroRoles = findDistroRoles(clusterCreate);
if (!clusterCreate.getDistro().equalsIgnoreCase(
com.vmware.bdd.utils.Constants.MAPR_VENDOR)) {
clusterCreate.validateClusterCreate(failedMsgList, warningMsgList,
distroRoles);
} else {
clusterCreate.validateClusterCreateOfMapr(failedMsgList,
distroRoles);
}
}
// give a warning message if both type and specFilePath are specified
if (type != null && specFilePath != null) {
warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT);
}
if (!failedMsgList.isEmpty()) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
return;
}
// rest invocation
try {
if (!CommandsUtils.showWarningMsg(clusterCreate.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
CommandsUtils.getExceptionMessage(e));
}
}
/**
* notify user which network Serengeti will pick up for mgt/hdfs/mapred
* @param networkConfig
* @param warningMsgList
*/
private void notifyNetsUsage(Map<NetTrafficType, List<String>> networkConfig,
List<String> warningMsgList) {
if (!networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)) {
return;
}
String mgtNetwork = networkConfig.get(NetTrafficType.MGT_NETWORK).get(0);
String hdfsNetwork = mgtNetwork;
String mapredNetwork = mgtNetwork;
if (networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.get(NetTrafficType.HDFS_NETWORK).isEmpty()) {
hdfsNetwork = networkConfig.get(NetTrafficType.HDFS_NETWORK).get(0);
}
if (networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)
&& !networkConfig.get(NetTrafficType.MAPRED_NETWORK).isEmpty()) {
mapredNetwork = networkConfig.get(NetTrafficType.MAPRED_NETWORK).get(0);
}
StringBuffer netsUsage = new StringBuffer().append("Hadoop will use network ")
.append(mgtNetwork).append(" for management, ")
.append(hdfsNetwork).append(" for hdfs traffic, and ")
.append(mapredNetwork).append(" for mapreduce traffic");
warningMsgList.add(netsUsage.toString());
}
private String getPassword() {
String firstPassword = getInputedPassword(Constants.ENTER_PASSWORD);
if (firstPassword == null) {
return null;
}
String secondPassword = getInputedPassword(Constants.CONFIRM_PASSWORD);
if (secondPassword == null) {
return null;
}
if (!firstPassword.equals(secondPassword)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_CONFIRMATION_FAILED);
return null;
}
return firstPassword;
}
private String getInputedPassword(String promptMsg) {
try {
ConsoleReader reader = new ConsoleReader();
reader.setDefaultPrompt(promptMsg);
String password = "";
password = reader.readLine(Character.valueOf('*'));
if (isValidPassword(password)) {
return password;
} else {
return null;
}
} catch (IOException e) {
return null;
}
}
private boolean isValidPassword(String password) {
if (password.length() < Constants.PASSWORD_MIN_LENGTH
|| password.length() > Constants.PASSWORD_MAX_LENGTH) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_LENGTH_INVALID);
return false;
}
return true;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(detail);
if (clusters != null && clusters.length > 0) {
Arrays.sort(clusters);
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name, detail);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
printSeperator();
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = false, help = "the cluster spec file path") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
// rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The resized number of instances. It should be larger that existing one") final int instanceNum,
@CliOption(key = { "cpuNumPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of vCPU for the nodes in this group") final int cpuNumber,
@CliOption(key = { "memCapacityMbPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of memory size in Mb for the nodes in this group") final long memory) {
if ((instanceNum > 0 && cpuNumber == 0 && memory == 0)
|| (instanceNum == 0 && (cpuNumber > 0 || memory > 0))) {
try {
ClusterRead cluster = restClient.get(name, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name
+ " does not exist.");
return;
}
// disallow scale out zookeeper node group.
List<NodeGroupRead> ngs = cluster.getNodeGroups();
boolean found = false;
for (NodeGroupRead ng : ngs) {
if (ng.getName().equals(nodeGroup)) {
found = true;
if (ng.getRoles() != null
&& ng.getRoles().contains(
HadoopRole.ZOOKEEPER_ROLE.toString())
&& instanceNum > 1) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.ZOOKEEPER_NOT_RESIZE);
return;
}
break;
}
}
if (!found) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup
+ " does not exist.");
return;
}
TaskRead taskRead = null;
if (instanceNum > 0) {
restClient.resize(name, nodeGroup, instanceNum);
} else if (cpuNumber > 0 || memory > 0) {
if (cluster.getStatus().ordinal() != ClusterStatus.RUNNING
.ordinal()) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Cluster must be in 'RUNNING' state to scale up/down");
return;
}
ResourceScale resScale =
new ResourceScale(name, nodeGroup, cpuNumber, memory);
taskRead = restClient.scale(resScale);
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
if (taskRead != null) {
System.out.println();
printScaleReport(taskRead, name, nodeGroup);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
if (instanceNum > 0 && (cpuNumber > 0 || memory > 0)) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Can not scale out and scale up/down at the same time, you have to run those commands separately");
} else if (instanceNum == 0 && cpuNumber == 0 && memory == 0) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"You must specify at least one positive value for instanceNum, cpuNumPerNode, or memCapacityPerNode");
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ (instanceNum < 0 ? " instanceNum=" + instanceNum + "," : "")
+ (cpuNumber < 0 ? " cpuNumPerNode=" + cpuNumber + "," : "")
+ (memory < 0 ? " memCapacityMbPerNode=" + memory : ""));
}
}
}
private void printScaleReport(TaskRead taskRead, String clusterName,
String nodeGroupName) {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
setNodeStatusInfo(failedNodes, nodeGroups);
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
columnNamesWithGetMethodNames.put("IP", Arrays.asList("getIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("CPU", Arrays.asList("getCpuNumber"));
columnNamesWithGetMethodNames.put("MEM(MB)", Arrays.asList("getMemory"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
columnNamesWithGetMethodNames.put("NOTES",
Arrays.asList("getErrorMessage"));
try {
System.out.println("The resized node group: " + nodeGroupName);
System.out
.println("The current resized nodes: " + succeedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The failed resized nodes: " + failedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
throw new CliRestException(e.getMessage());
}
}
private void setNodeStatusInfo(List<NodeStatus> nodes,
List<NodeGroupRead> nodeGroups) {
for (NodeStatus nodeStatus : nodes) {
NodeRead node = getNodeRead(nodeStatus.getNodeName(), nodeGroups);
if (node != null) {
// only show the management Ip currently
nodeStatus.setIp(node.fetchMgtIp());
nodeStatus.setStatus(node.getStatus());
nodeStatus.setCpuNumber(node.getCpuNumber());
nodeStatus.setMemory(node.getMemory());
}
}
}
@CliCommand(value = "cluster setParam", help = "set cluster parameters")
public void setParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "elasticityMode" }, mandatory = false, help = "The elasticity mode: AUTO, MANUAL") final String elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, help = "The minimum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, help = "The maximum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, help = "The number of instances powered on (valid in manual elasticity mode)") final Integer targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, help = "The relative disk I/O priorities: HIGH, NORNAL, LOW") final String ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type for elasticity params
if ((elasticityMode != null || minComputeNodeNum != null || maxComputeNodeNum != null || targetComputeNodeNum != null)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
ElasticityMode mode = null;
//validate the input of elasticityMode
if (elasticityMode != null) {
try {
mode = ElasticityMode.valueOf(elasticityMode.toUpperCase());
} catch (IllegalArgumentException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " elasticityMode = " + elasticityMode);
return;
}
}
Boolean enableAuto = null;
if (mode != null) {
enableAuto = (mode == ElasticityMode.AUTO) ? true : false;
}
//validate the input parameters
if (!cluster.validateSetParamParameters(targetComputeNodeNum,
minComputeNodeNum, maxComputeNodeNum, enableAuto)) {
return;
}
//validate the input of ioShares
Priority ioPriority = null;
if (ioShares != null) {
try {
ioPriority = Priority.valueOf(ioShares.toUpperCase());
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "ioShares = " + ioShares);
return;
}
}
ElasticityRequestBody requestBody = new ElasticityRequestBody();
requestBody.setEnableAuto(enableAuto);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
} else {
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
} else {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
requestBody.setIoPriority(ioPriority);
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_ADJUST);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
if (targetComputeNodeNum != null) {
System.out.println("For AUTO scaling mode, targetComputeNodeNum will be ignored.");
}
} else {
if (minComputeNodeNum != null || maxComputeNodeNum != null) {
System.out.println("For MANUAL scaling mode, minComputeNodeNum and maxComputeNodeNum will be ignored.");
}
}
}
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster resetParam", help = "reset cluster parameters")
public void resetParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "all" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset all parameters") final boolean all,
@CliOption(key = { "elasticityMode" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset elasticity mode to MANUAL") final boolean elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset minComputeNodeNum to -1") final boolean minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset maxComputeNodeNum to -1") final boolean maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset targetComputeNodeNum to -1(activate all compute nodes)") final boolean targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset disk I/O priorities to LOW") final boolean ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type
if ((elasticityMode || minComputeNodeNum || maxComputeNodeNum || targetComputeNodeNum)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
// reset Auto Elasticity parameters. The default values are:
// elasticityMode: manual
// targetComputeNodes: -1
// minComputeNodes: -1
// maxComputeNodes: -1
// ioShares: normal
ElasticityRequestBody requestBody = new ElasticityRequestBody();
if (elasticityMode || all) {
requestBody.setEnableAuto(false);
}
if (minComputeNodeNum || all) {
requestBody.setMinComputeNodeNum(-1);
}
if (maxComputeNodeNum || all) {
requestBody.setMaxComputeNodeNum(-1);
}
if (targetComputeNodeNum || all) {
requestBody.setActiveComputeNodeNum(-1);
}
if (ioShares || all) {
requestBody.setIoPriority(Priority.NORMAL);
}
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_RESET);
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
boolean noCluster = false;
try {
if (info) {
if (name != null) {
System.out
.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0)
&& (jtUrl == null || jtUrl.length() == 0)) {
System.out
.println("There is no targeted cluster. Run \"cluster target --name\" command first.");
return;
}
if (targetClusterName != null && targetClusterName.length() > 0) {
System.out.println("Cluster : " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url : " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url : " + jtUrl);
}
if (hiveServerUrl != null && hiveServerUrl.length() > 0) {
System.out.println("Hive server info: " + hiveServerUrl);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(false);
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
} else {
noCluster = true;
}
} else {
cluster = restClient.get(name, false);
}
if (cluster == null) {
if (noCluster) {
System.out
.println("There is no available cluster for targeting.");
} else {
System.out.println("Failed to target cluster: The cluster "
+ name + " not found");
}
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
} else {
targetClusterName = cluster.getName();
boolean hasHDFS = false;
boolean hasHiveServer = false;
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).fetchMgtIp();
setNameNode(nameNodeIP);
hasHDFS = true;
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).fetchMgtIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException(
"no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).fetchMgtIp();
setHiveServerAddress(hiveServerIP);
hasHiveServer = true;
} else {
throw new CliRestException(
"no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
hasHDFS = true;
}
if (!hasHDFS) {
setFsURL("");
}
if (!hasHiveServer) {
this.setHiveServerUrl("");
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
setJobTrackerURL(jobTrackerUrl);
}
private void setJobTrackerURL(String jobTrackerUrl) {
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServerAddress(String hiveServerAddress) {
try {
hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
private void setHiveServerUrl(String hiveServerUrl) {
this.hiveServerUrl = hiveServerUrl;
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name, false);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation,
warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: "
+ Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!CommandsUtils.showWarningMsg(clusterConfig.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
}
@CliCommand(value = "cluster fix", help = "Fix a cluster failure")
public void fixCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "disk" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Recover a disk failure") final boolean isDiskFailure,
@CliOption(key = { "parallel" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether use parallel way to recovery node or not") final boolean parallel,
@CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name which failure belong to") final String nodeGroupName) {
try {
TaskRead taskRead = null;
if (!isDiskFailure) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_SPECIFY_DISK);
return;
} else {
FixDiskRequestBody requestBody = new FixDiskRequestBody();
requestBody.setParallel(parallel);
if (!CommandsUtils.isBlank(nodeGroupName)) {
requestBody.setNodeGroupName(nodeGroupName);
}
taskRead = restClient.fixDisk(clusterName, requestBody);
if (taskRead == null) {
return;
}
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_FIX);
System.out.println();
printClusterFixReport(taskRead, clusterName);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private void printClusterFixReport(TaskRead taskRead, String clusterName)
throws Exception {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
System.out.println("The fixed nodes: " + succeedNodes.size());
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
- columnNamesWithGetMethodNames.put("IP", Arrays.asList("fetchMgtIp"));
+ columnNamesWithGetMethodNames.put("IP", Arrays.asList("getIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The recovery-failed nodes: " + failedNodes.size());
setNodeStatusInfo(failedNodes, nodeGroups);
columnNamesWithGetMethodNames.put("Error Message",
Arrays.asList("getErrorMessage"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
}
private NodeRead getNodeRead(String nodeName, List<NodeGroupRead> nodeGroups) {
for (NodeGroupRead nodeGroup : nodeGroups) {
List<NodeRead> nodes = nodeGroup.getInstances();
for (NodeRead node : nodes) {
if (node.getName().equals(nodeName)) {
return node;
}
}
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private Set<String> getAllNetworkNames() {
Set<String> allNetworks = new HashSet<String>();
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks) {
allNetworks.add(network.getName());
}
}
return allNetworks;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputDynamicResourceInfo(ClusterRead cluster) {
TopologyType topology = cluster.getTopologyPolicy();
if (topology == null || topology == TopologyType.NONE) {
System.out.printf("cluster name: %s, distro: %s, status: %s",
cluster.getName(), cluster.getDistro(), cluster.getStatus());
} else {
System.out.printf(
"cluster name: %s, distro: %s, topology: %s, status: %s",
cluster.getName(), cluster.getDistro(), topology,
cluster.getStatus());
}
System.out.println();
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RUNNING_NODES,
Arrays.asList("getRunningNodesNum"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IOSHARES,
Arrays.asList("getStorage", "getShares"));
try {
CommandsUtils.printInTableFormat(ngColumnNamesWithGetMethodNames,
nodegroups.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
TopologyType topology = cluster.getTopologyPolicy();
String autoElasticityStatus;
String minComputeNodeNum = cluster.retrieveVhmMinNum();
String maxComputeNodeNum = cluster.retrieveVhmMaxNum();
if (cluster.getAutomationEnable() == null) {
autoElasticityStatus = "N/A";
minComputeNodeNum = "N/A";
maxComputeNodeNum = "N/A";
} else if (cluster.getAutomationEnable()) {
autoElasticityStatus = "Enable";
} else {
autoElasticityStatus = "Disable";
}
printSeperator();
// list cluster level params
LinkedHashMap<String, String> clusterParams =
new LinkedHashMap<String, String>();
clusterParams.put("CLUSTER NAME", cluster.getName());
clusterParams.put("DISTRO", cluster.getDistro());
if (topology != null && topology != TopologyType.NONE) {
clusterParams.put("TOPOLOGY", topology.toString());
}
clusterParams.put("AUTO ELASTIC", autoElasticityStatus);
clusterParams.put("MIN COMPUTE NODES NUM", minComputeNodeNum);
clusterParams.put("MAX COMPUTE NODES NUM", maxComputeNodeNum);
clusterParams.put("IO SHARES", cluster.getIoShares() == null ? ""
: cluster.getIoShares().toString());
clusterParams.put("STATUS", cluster.getStatus() == null ? "" : cluster
.getStatus().toString());
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
clusterParams.put("EXTERNAL HDFS", cluster.getExternalHDFS());
}
for (String key : clusterParams.keySet()) {
System.out.printf(Constants.OUTPUT_INDENT + "%-26s:"
+ Constants.OUTPUT_INDENT + "%s\n", key, clusterParams.get(key));
}
System.out.println();
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
if (topology == TopologyType.RACK_AS_RACK
|| topology == TopologyType.HVE) {
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RACK,
Arrays.asList("getRack"));
}
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("fetchMgtIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HDFS_IP, Arrays.asList("fetchHdfsIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MAPRED_IP, Arrays.asList("fetchMapredIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TASK,
Arrays.asList("getAction"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNamesClone =
(LinkedHashMap<String, List<String>>) nColumnNamesWithGetMethodNames.clone();
if (!nodes.isEmpty() &&
(nodes.get(0).getIpConfigs() == null
|| (!nodes.get(0).getIpConfigs().containsKey(NetTrafficType.HDFS_NETWORK)
&& !nodes.get(0).getIpConfigs().containsKey(NetTrafficType.MAPRED_NETWORK)))) {
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_HDFS_IP);
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_MAPRED_IP);
}
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNamesClone, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
}
printSeperator();
}
private void printSeperator() {
StringBuffer seperator =
new StringBuffer().append(Constants.OUTPUT_INDENT);
for (int i = 0; i < Constants.SEPERATOR_LEN; i++) {
seperator.append("=");
}
System.out.println(seperator.toString());
System.out.println();
}
private void showFailedMsg(String name, List<String> failedMsgList) {
// cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(msg);
}
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster,
boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
/*
* Validate a configuration of the cluster at first. Validate configurations
* of all of node groups then. And merge the failed info which have been
* producted by validation between cluster level and node group level.
*/
private ValidateResult validateConfiguration(ClusterCreate cluster,
ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null
&& !cluster.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
validateResult.setNoExistFileNames(vr.getNoExistFileNames());
}
}
List<String> failureNames = new LinkedList<String>();
Map<String, List<String>> noExistingFileNamesMap =
new HashMap<String, List<String>>();
failureNames.addAll(validateResult.getFailureNames());
noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames());
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null
&& !nodeGroup.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
// merge failed names between cluster level and node group level.
for (String failureName : vr.getFailureNames()) {
if (!failureNames.contains(failureName)) {
failureNames.add(failureName);
}
}
// merge no existing file names between cluster level and node
// group level
for (Entry<String, List<String>> noExistingFileNames : vr
.getNoExistFileNames().entrySet()) {
String configType = noExistingFileNames.getKey();
if (noExistingFileNamesMap.containsKey(configType)) {
List<String> noExistingFilesTemp =
noExistingFileNames.getValue();
List<String> noExistingFiles =
noExistingFileNamesMap.get(configType);
for (String fileName : noExistingFilesTemp) {
if (!noExistingFiles.contains(fileName)) {
noExistingFiles.add(fileName);
}
}
noExistingFileNamesMap.put(configType, noExistingFiles);
} else {
noExistingFileNamesMap.put(configType,
noExistingFileNames.getValue());
}
}
}
}
}
validateResult.setFailureNames(failureNames);
validateResult.setNoExistFileNames(noExistingFileNamesMap);
return validateResult;
}
private void addWhiteListWarning(final String clusterName,
ValidateResult whiteListResult, List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
}
} else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
String failureNameWarningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
warningMsgList.add(failureNameWarningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult,
List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(),
Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING
+ Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
if (warningList != null) {
warningList.add(warningMsg);
}
}
}
private String getValidateWarningMsg(List<String> failureNames,
String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private String getValidateWarningMsg(
Map<String, List<String>> noExistingFilesMap) {
StringBuilder warningMsgBuff = new StringBuilder();
if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap
.entrySet()) {
List<String> noExistingFileNames = noExistingFilesEntry.getValue();
for (String noExistingFileName : noExistingFileNames) {
warningMsgBuff.append(noExistingFileName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (noExistingFileNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append("not existing in ");
warningMsgBuff.append(noExistingFilesEntry.getKey() + " scope , ");
}
warningMsgBuff.replace(warningMsgBuff.length() - 2,
warningMsgBuff.length(), ". ");
warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
}
return warningMsgBuff.toString();
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off", "on", "ft");
if (nodeGroups != null) {
for (NodeGroupCreate group : nodeGroups) {
if (!haFlagList.contains(group.getHaFlag().toLowerCase())) {
return false;
}
}
}
return true;
}
}
| true | true | public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type,
@CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name used for management") final String networkName,
@CliOption(key = { "hdfsNetworkName" }, mandatory = false, help = "Network Name for HDFS traffic.") final String hdfsNetworkName,
@CliOption(key = { "mapredNetworkName" }, mandatory = false, help = "Network Name for MapReduce traffic") final String mapredNetworkName,
@CliOption(key = { "topology" }, mandatory = false, help = "You must specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes,
@CliOption(key = { "password" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Answer 'yes' to set password for all VMs in this cluster.") final boolean setClusterPassword) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
} else if (name.indexOf(" ") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_BLANK_SPACE);
return;
}
// process resume
if (resume && setClusterPassword) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.RESUME_DONOT_NEED_SET_PASSWORD);
return;
} else if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (setClusterPassword) {
String password = getPassword();
//user would like to set password, but failed to enter
//a valid one, quit cluster create
if (password == null) {
return;
} else {
clusterCreate.setPassword(password);
}
}
if (type != null) {
ClusterType clusterType = ClusterType.getByDescription(type);
if (clusterType == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "type=" + type);
return;
}
clusterCreate.setType(clusterType);
} else if (specFilePath == null) {
// create Hadoop (HDFS + MapReduce) cluster as default
clusterCreate.setType(ClusterType.HDFS_MAPRED);
}
if (topology != null) {
try {
clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology));
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "topologyType=" + topology);
return;
}
} else {
clusterCreate.setTopologyPolicy(TopologyType.NONE);
}
try {
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
} else {
String defaultDistroName =
clusterCreate.getDefaultDistroName(distroRestClient.getAll());
if (CommandsUtils.isBlank(defaultDistroName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM__NO_DEFAULT_DISTRO);
return;
} else {
clusterCreate.setDistro(defaultDistroName);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro());
clusterCreate.setDistroVendor(distroRead.getVendor());
clusterCreate.setDistroVersion(distroRead.getVersion());
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> failedMsgList = new ArrayList<String>();
List<String> warningMsgList = new ArrayList<String>();
Set<String> allNetworkNames = new HashSet<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setSpecFile(true);
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation,
warningMsgList);
clusterCreate.validateNodeGroupNames();
if (!validateHAInfo(clusterCreate.getNodeGroups())) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
allNetworkNames = getAllNetworkNames();
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
if (allNetworkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CANNOT_FIND_NETWORK);
return;
}
Map<NetTrafficType, List<String>> networkConfig = new HashMap<NetTrafficType, List<String>>();
if (networkName == null) {
if (allNetworkNames.size() == 1) {
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).addAll(allNetworkNames);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
} else {
if (!allNetworkNames.contains(networkName)
|| (hdfsNetworkName != null && !allNetworkNames.contains(hdfsNetworkName))
|| (mapredNetworkName != null && !allNetworkNames.contains(mapredNetworkName))) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + allNetworkNames.toString());
return;
}
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).add(networkName);
if (hdfsNetworkName != null) {
networkConfig.put(NetTrafficType.HDFS_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.HDFS_NETWORK).add(hdfsNetworkName);
}
if (mapredNetworkName != null) {
networkConfig.put(NetTrafficType.MAPRED_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MAPRED_NETWORK).add(mapredNetworkName);
}
}
notifyNetsUsage(networkConfig, warningMsgList);
clusterCreate.setNetworkConfig(networkConfig);
clusterCreate.validateCDHVersion(warningMsgList);
// Validate that the specified file is correct json format and proper
// value.
if (specFilePath != null) {
List<String> distroRoles = findDistroRoles(clusterCreate);
if (!clusterCreate.getDistro().equalsIgnoreCase(
com.vmware.bdd.utils.Constants.MAPR_VENDOR)) {
clusterCreate.validateClusterCreate(failedMsgList, warningMsgList,
distroRoles);
} else {
clusterCreate.validateClusterCreateOfMapr(failedMsgList,
distroRoles);
}
}
// give a warning message if both type and specFilePath are specified
if (type != null && specFilePath != null) {
warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT);
}
if (!failedMsgList.isEmpty()) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
return;
}
// rest invocation
try {
if (!CommandsUtils.showWarningMsg(clusterCreate.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
CommandsUtils.getExceptionMessage(e));
}
}
/**
* notify user which network Serengeti will pick up for mgt/hdfs/mapred
* @param networkConfig
* @param warningMsgList
*/
private void notifyNetsUsage(Map<NetTrafficType, List<String>> networkConfig,
List<String> warningMsgList) {
if (!networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)) {
return;
}
String mgtNetwork = networkConfig.get(NetTrafficType.MGT_NETWORK).get(0);
String hdfsNetwork = mgtNetwork;
String mapredNetwork = mgtNetwork;
if (networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.get(NetTrafficType.HDFS_NETWORK).isEmpty()) {
hdfsNetwork = networkConfig.get(NetTrafficType.HDFS_NETWORK).get(0);
}
if (networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)
&& !networkConfig.get(NetTrafficType.MAPRED_NETWORK).isEmpty()) {
mapredNetwork = networkConfig.get(NetTrafficType.MAPRED_NETWORK).get(0);
}
StringBuffer netsUsage = new StringBuffer().append("Hadoop will use network ")
.append(mgtNetwork).append(" for management, ")
.append(hdfsNetwork).append(" for hdfs traffic, and ")
.append(mapredNetwork).append(" for mapreduce traffic");
warningMsgList.add(netsUsage.toString());
}
private String getPassword() {
String firstPassword = getInputedPassword(Constants.ENTER_PASSWORD);
if (firstPassword == null) {
return null;
}
String secondPassword = getInputedPassword(Constants.CONFIRM_PASSWORD);
if (secondPassword == null) {
return null;
}
if (!firstPassword.equals(secondPassword)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_CONFIRMATION_FAILED);
return null;
}
return firstPassword;
}
private String getInputedPassword(String promptMsg) {
try {
ConsoleReader reader = new ConsoleReader();
reader.setDefaultPrompt(promptMsg);
String password = "";
password = reader.readLine(Character.valueOf('*'));
if (isValidPassword(password)) {
return password;
} else {
return null;
}
} catch (IOException e) {
return null;
}
}
private boolean isValidPassword(String password) {
if (password.length() < Constants.PASSWORD_MIN_LENGTH
|| password.length() > Constants.PASSWORD_MAX_LENGTH) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_LENGTH_INVALID);
return false;
}
return true;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(detail);
if (clusters != null && clusters.length > 0) {
Arrays.sort(clusters);
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name, detail);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
printSeperator();
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = false, help = "the cluster spec file path") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
// rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The resized number of instances. It should be larger that existing one") final int instanceNum,
@CliOption(key = { "cpuNumPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of vCPU for the nodes in this group") final int cpuNumber,
@CliOption(key = { "memCapacityMbPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of memory size in Mb for the nodes in this group") final long memory) {
if ((instanceNum > 0 && cpuNumber == 0 && memory == 0)
|| (instanceNum == 0 && (cpuNumber > 0 || memory > 0))) {
try {
ClusterRead cluster = restClient.get(name, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name
+ " does not exist.");
return;
}
// disallow scale out zookeeper node group.
List<NodeGroupRead> ngs = cluster.getNodeGroups();
boolean found = false;
for (NodeGroupRead ng : ngs) {
if (ng.getName().equals(nodeGroup)) {
found = true;
if (ng.getRoles() != null
&& ng.getRoles().contains(
HadoopRole.ZOOKEEPER_ROLE.toString())
&& instanceNum > 1) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.ZOOKEEPER_NOT_RESIZE);
return;
}
break;
}
}
if (!found) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup
+ " does not exist.");
return;
}
TaskRead taskRead = null;
if (instanceNum > 0) {
restClient.resize(name, nodeGroup, instanceNum);
} else if (cpuNumber > 0 || memory > 0) {
if (cluster.getStatus().ordinal() != ClusterStatus.RUNNING
.ordinal()) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Cluster must be in 'RUNNING' state to scale up/down");
return;
}
ResourceScale resScale =
new ResourceScale(name, nodeGroup, cpuNumber, memory);
taskRead = restClient.scale(resScale);
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
if (taskRead != null) {
System.out.println();
printScaleReport(taskRead, name, nodeGroup);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
if (instanceNum > 0 && (cpuNumber > 0 || memory > 0)) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Can not scale out and scale up/down at the same time, you have to run those commands separately");
} else if (instanceNum == 0 && cpuNumber == 0 && memory == 0) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"You must specify at least one positive value for instanceNum, cpuNumPerNode, or memCapacityPerNode");
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ (instanceNum < 0 ? " instanceNum=" + instanceNum + "," : "")
+ (cpuNumber < 0 ? " cpuNumPerNode=" + cpuNumber + "," : "")
+ (memory < 0 ? " memCapacityMbPerNode=" + memory : ""));
}
}
}
private void printScaleReport(TaskRead taskRead, String clusterName,
String nodeGroupName) {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
setNodeStatusInfo(failedNodes, nodeGroups);
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
columnNamesWithGetMethodNames.put("IP", Arrays.asList("getIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("CPU", Arrays.asList("getCpuNumber"));
columnNamesWithGetMethodNames.put("MEM(MB)", Arrays.asList("getMemory"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
columnNamesWithGetMethodNames.put("NOTES",
Arrays.asList("getErrorMessage"));
try {
System.out.println("The resized node group: " + nodeGroupName);
System.out
.println("The current resized nodes: " + succeedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The failed resized nodes: " + failedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
throw new CliRestException(e.getMessage());
}
}
private void setNodeStatusInfo(List<NodeStatus> nodes,
List<NodeGroupRead> nodeGroups) {
for (NodeStatus nodeStatus : nodes) {
NodeRead node = getNodeRead(nodeStatus.getNodeName(), nodeGroups);
if (node != null) {
// only show the management Ip currently
nodeStatus.setIp(node.fetchMgtIp());
nodeStatus.setStatus(node.getStatus());
nodeStatus.setCpuNumber(node.getCpuNumber());
nodeStatus.setMemory(node.getMemory());
}
}
}
@CliCommand(value = "cluster setParam", help = "set cluster parameters")
public void setParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "elasticityMode" }, mandatory = false, help = "The elasticity mode: AUTO, MANUAL") final String elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, help = "The minimum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, help = "The maximum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, help = "The number of instances powered on (valid in manual elasticity mode)") final Integer targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, help = "The relative disk I/O priorities: HIGH, NORNAL, LOW") final String ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type for elasticity params
if ((elasticityMode != null || minComputeNodeNum != null || maxComputeNodeNum != null || targetComputeNodeNum != null)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
ElasticityMode mode = null;
//validate the input of elasticityMode
if (elasticityMode != null) {
try {
mode = ElasticityMode.valueOf(elasticityMode.toUpperCase());
} catch (IllegalArgumentException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " elasticityMode = " + elasticityMode);
return;
}
}
Boolean enableAuto = null;
if (mode != null) {
enableAuto = (mode == ElasticityMode.AUTO) ? true : false;
}
//validate the input parameters
if (!cluster.validateSetParamParameters(targetComputeNodeNum,
minComputeNodeNum, maxComputeNodeNum, enableAuto)) {
return;
}
//validate the input of ioShares
Priority ioPriority = null;
if (ioShares != null) {
try {
ioPriority = Priority.valueOf(ioShares.toUpperCase());
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "ioShares = " + ioShares);
return;
}
}
ElasticityRequestBody requestBody = new ElasticityRequestBody();
requestBody.setEnableAuto(enableAuto);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
} else {
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
} else {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
requestBody.setIoPriority(ioPriority);
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_ADJUST);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
if (targetComputeNodeNum != null) {
System.out.println("For AUTO scaling mode, targetComputeNodeNum will be ignored.");
}
} else {
if (minComputeNodeNum != null || maxComputeNodeNum != null) {
System.out.println("For MANUAL scaling mode, minComputeNodeNum and maxComputeNodeNum will be ignored.");
}
}
}
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster resetParam", help = "reset cluster parameters")
public void resetParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "all" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset all parameters") final boolean all,
@CliOption(key = { "elasticityMode" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset elasticity mode to MANUAL") final boolean elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset minComputeNodeNum to -1") final boolean minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset maxComputeNodeNum to -1") final boolean maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset targetComputeNodeNum to -1(activate all compute nodes)") final boolean targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset disk I/O priorities to LOW") final boolean ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type
if ((elasticityMode || minComputeNodeNum || maxComputeNodeNum || targetComputeNodeNum)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
// reset Auto Elasticity parameters. The default values are:
// elasticityMode: manual
// targetComputeNodes: -1
// minComputeNodes: -1
// maxComputeNodes: -1
// ioShares: normal
ElasticityRequestBody requestBody = new ElasticityRequestBody();
if (elasticityMode || all) {
requestBody.setEnableAuto(false);
}
if (minComputeNodeNum || all) {
requestBody.setMinComputeNodeNum(-1);
}
if (maxComputeNodeNum || all) {
requestBody.setMaxComputeNodeNum(-1);
}
if (targetComputeNodeNum || all) {
requestBody.setActiveComputeNodeNum(-1);
}
if (ioShares || all) {
requestBody.setIoPriority(Priority.NORMAL);
}
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_RESET);
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
boolean noCluster = false;
try {
if (info) {
if (name != null) {
System.out
.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0)
&& (jtUrl == null || jtUrl.length() == 0)) {
System.out
.println("There is no targeted cluster. Run \"cluster target --name\" command first.");
return;
}
if (targetClusterName != null && targetClusterName.length() > 0) {
System.out.println("Cluster : " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url : " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url : " + jtUrl);
}
if (hiveServerUrl != null && hiveServerUrl.length() > 0) {
System.out.println("Hive server info: " + hiveServerUrl);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(false);
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
} else {
noCluster = true;
}
} else {
cluster = restClient.get(name, false);
}
if (cluster == null) {
if (noCluster) {
System.out
.println("There is no available cluster for targeting.");
} else {
System.out.println("Failed to target cluster: The cluster "
+ name + " not found");
}
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
} else {
targetClusterName = cluster.getName();
boolean hasHDFS = false;
boolean hasHiveServer = false;
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).fetchMgtIp();
setNameNode(nameNodeIP);
hasHDFS = true;
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).fetchMgtIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException(
"no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).fetchMgtIp();
setHiveServerAddress(hiveServerIP);
hasHiveServer = true;
} else {
throw new CliRestException(
"no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
hasHDFS = true;
}
if (!hasHDFS) {
setFsURL("");
}
if (!hasHiveServer) {
this.setHiveServerUrl("");
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
setJobTrackerURL(jobTrackerUrl);
}
private void setJobTrackerURL(String jobTrackerUrl) {
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServerAddress(String hiveServerAddress) {
try {
hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
private void setHiveServerUrl(String hiveServerUrl) {
this.hiveServerUrl = hiveServerUrl;
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name, false);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation,
warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: "
+ Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!CommandsUtils.showWarningMsg(clusterConfig.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
}
@CliCommand(value = "cluster fix", help = "Fix a cluster failure")
public void fixCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "disk" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Recover a disk failure") final boolean isDiskFailure,
@CliOption(key = { "parallel" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether use parallel way to recovery node or not") final boolean parallel,
@CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name which failure belong to") final String nodeGroupName) {
try {
TaskRead taskRead = null;
if (!isDiskFailure) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_SPECIFY_DISK);
return;
} else {
FixDiskRequestBody requestBody = new FixDiskRequestBody();
requestBody.setParallel(parallel);
if (!CommandsUtils.isBlank(nodeGroupName)) {
requestBody.setNodeGroupName(nodeGroupName);
}
taskRead = restClient.fixDisk(clusterName, requestBody);
if (taskRead == null) {
return;
}
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_FIX);
System.out.println();
printClusterFixReport(taskRead, clusterName);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private void printClusterFixReport(TaskRead taskRead, String clusterName)
throws Exception {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
System.out.println("The fixed nodes: " + succeedNodes.size());
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
columnNamesWithGetMethodNames.put("IP", Arrays.asList("fetchMgtIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The recovery-failed nodes: " + failedNodes.size());
setNodeStatusInfo(failedNodes, nodeGroups);
columnNamesWithGetMethodNames.put("Error Message",
Arrays.asList("getErrorMessage"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
}
private NodeRead getNodeRead(String nodeName, List<NodeGroupRead> nodeGroups) {
for (NodeGroupRead nodeGroup : nodeGroups) {
List<NodeRead> nodes = nodeGroup.getInstances();
for (NodeRead node : nodes) {
if (node.getName().equals(nodeName)) {
return node;
}
}
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private Set<String> getAllNetworkNames() {
Set<String> allNetworks = new HashSet<String>();
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks) {
allNetworks.add(network.getName());
}
}
return allNetworks;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputDynamicResourceInfo(ClusterRead cluster) {
TopologyType topology = cluster.getTopologyPolicy();
if (topology == null || topology == TopologyType.NONE) {
System.out.printf("cluster name: %s, distro: %s, status: %s",
cluster.getName(), cluster.getDistro(), cluster.getStatus());
} else {
System.out.printf(
"cluster name: %s, distro: %s, topology: %s, status: %s",
cluster.getName(), cluster.getDistro(), topology,
cluster.getStatus());
}
System.out.println();
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RUNNING_NODES,
Arrays.asList("getRunningNodesNum"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IOSHARES,
Arrays.asList("getStorage", "getShares"));
try {
CommandsUtils.printInTableFormat(ngColumnNamesWithGetMethodNames,
nodegroups.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
TopologyType topology = cluster.getTopologyPolicy();
String autoElasticityStatus;
String minComputeNodeNum = cluster.retrieveVhmMinNum();
String maxComputeNodeNum = cluster.retrieveVhmMaxNum();
if (cluster.getAutomationEnable() == null) {
autoElasticityStatus = "N/A";
minComputeNodeNum = "N/A";
maxComputeNodeNum = "N/A";
} else if (cluster.getAutomationEnable()) {
autoElasticityStatus = "Enable";
} else {
autoElasticityStatus = "Disable";
}
printSeperator();
// list cluster level params
LinkedHashMap<String, String> clusterParams =
new LinkedHashMap<String, String>();
clusterParams.put("CLUSTER NAME", cluster.getName());
clusterParams.put("DISTRO", cluster.getDistro());
if (topology != null && topology != TopologyType.NONE) {
clusterParams.put("TOPOLOGY", topology.toString());
}
clusterParams.put("AUTO ELASTIC", autoElasticityStatus);
clusterParams.put("MIN COMPUTE NODES NUM", minComputeNodeNum);
clusterParams.put("MAX COMPUTE NODES NUM", maxComputeNodeNum);
clusterParams.put("IO SHARES", cluster.getIoShares() == null ? ""
: cluster.getIoShares().toString());
clusterParams.put("STATUS", cluster.getStatus() == null ? "" : cluster
.getStatus().toString());
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
clusterParams.put("EXTERNAL HDFS", cluster.getExternalHDFS());
}
for (String key : clusterParams.keySet()) {
System.out.printf(Constants.OUTPUT_INDENT + "%-26s:"
+ Constants.OUTPUT_INDENT + "%s\n", key, clusterParams.get(key));
}
System.out.println();
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
if (topology == TopologyType.RACK_AS_RACK
|| topology == TopologyType.HVE) {
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RACK,
Arrays.asList("getRack"));
}
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("fetchMgtIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HDFS_IP, Arrays.asList("fetchHdfsIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MAPRED_IP, Arrays.asList("fetchMapredIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TASK,
Arrays.asList("getAction"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNamesClone =
(LinkedHashMap<String, List<String>>) nColumnNamesWithGetMethodNames.clone();
if (!nodes.isEmpty() &&
(nodes.get(0).getIpConfigs() == null
|| (!nodes.get(0).getIpConfigs().containsKey(NetTrafficType.HDFS_NETWORK)
&& !nodes.get(0).getIpConfigs().containsKey(NetTrafficType.MAPRED_NETWORK)))) {
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_HDFS_IP);
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_MAPRED_IP);
}
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNamesClone, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
}
printSeperator();
}
private void printSeperator() {
StringBuffer seperator =
new StringBuffer().append(Constants.OUTPUT_INDENT);
for (int i = 0; i < Constants.SEPERATOR_LEN; i++) {
seperator.append("=");
}
System.out.println(seperator.toString());
System.out.println();
}
private void showFailedMsg(String name, List<String> failedMsgList) {
// cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(msg);
}
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster,
boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
/*
* Validate a configuration of the cluster at first. Validate configurations
* of all of node groups then. And merge the failed info which have been
* producted by validation between cluster level and node group level.
*/
private ValidateResult validateConfiguration(ClusterCreate cluster,
ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null
&& !cluster.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
validateResult.setNoExistFileNames(vr.getNoExistFileNames());
}
}
List<String> failureNames = new LinkedList<String>();
Map<String, List<String>> noExistingFileNamesMap =
new HashMap<String, List<String>>();
failureNames.addAll(validateResult.getFailureNames());
noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames());
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null
&& !nodeGroup.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
// merge failed names between cluster level and node group level.
for (String failureName : vr.getFailureNames()) {
if (!failureNames.contains(failureName)) {
failureNames.add(failureName);
}
}
// merge no existing file names between cluster level and node
// group level
for (Entry<String, List<String>> noExistingFileNames : vr
.getNoExistFileNames().entrySet()) {
String configType = noExistingFileNames.getKey();
if (noExistingFileNamesMap.containsKey(configType)) {
List<String> noExistingFilesTemp =
noExistingFileNames.getValue();
List<String> noExistingFiles =
noExistingFileNamesMap.get(configType);
for (String fileName : noExistingFilesTemp) {
if (!noExistingFiles.contains(fileName)) {
noExistingFiles.add(fileName);
}
}
noExistingFileNamesMap.put(configType, noExistingFiles);
} else {
noExistingFileNamesMap.put(configType,
noExistingFileNames.getValue());
}
}
}
}
}
validateResult.setFailureNames(failureNames);
validateResult.setNoExistFileNames(noExistingFileNamesMap);
return validateResult;
}
private void addWhiteListWarning(final String clusterName,
ValidateResult whiteListResult, List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
}
} else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
String failureNameWarningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
warningMsgList.add(failureNameWarningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult,
List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(),
Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING
+ Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
if (warningList != null) {
warningList.add(warningMsg);
}
}
}
private String getValidateWarningMsg(List<String> failureNames,
String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private String getValidateWarningMsg(
Map<String, List<String>> noExistingFilesMap) {
StringBuilder warningMsgBuff = new StringBuilder();
if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap
.entrySet()) {
List<String> noExistingFileNames = noExistingFilesEntry.getValue();
for (String noExistingFileName : noExistingFileNames) {
warningMsgBuff.append(noExistingFileName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (noExistingFileNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append("not existing in ");
warningMsgBuff.append(noExistingFilesEntry.getKey() + " scope , ");
}
warningMsgBuff.replace(warningMsgBuff.length() - 2,
warningMsgBuff.length(), ". ");
warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
}
return warningMsgBuff.toString();
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off", "on", "ft");
if (nodeGroups != null) {
for (NodeGroupCreate group : nodeGroups) {
if (!haFlagList.contains(group.getHaFlag().toLowerCase())) {
return false;
}
}
}
return true;
}
}
| public void createCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type,
@CliOption(key = { "distro" }, mandatory = false, help = "A hadoop distro name") final String distro,
@CliOption(key = { "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
@CliOption(key = { "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
@CliOption(key = { "networkName" }, mandatory = false, help = "Network Name used for management") final String networkName,
@CliOption(key = { "hdfsNetworkName" }, mandatory = false, help = "Network Name for HDFS traffic.") final String hdfsNetworkName,
@CliOption(key = { "mapredNetworkName" }, mandatory = false, help = "Network Name for MapReduce traffic") final String mapredNetworkName,
@CliOption(key = { "topology" }, mandatory = false, help = "You must specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology,
@CliOption(key = { "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes,
@CliOption(key = { "password" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Answer 'yes' to set password for all VMs in this cluster.") final boolean setClusterPassword) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
} else if (name.indexOf(" ") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_BLANK_SPACE);
return;
}
// process resume
if (resume && setClusterPassword) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.RESUME_DONOT_NEED_SET_PASSWORD);
return;
} else if (resume) {
resumeCreateCluster(name);
return;
}
// build ClusterCreate object
ClusterCreate clusterCreate = new ClusterCreate();
clusterCreate.setName(name);
if (setClusterPassword) {
String password = getPassword();
//user would like to set password, but failed to enter
//a valid one, quit cluster create
if (password == null) {
return;
} else {
clusterCreate.setPassword(password);
}
}
if (type != null) {
ClusterType clusterType = ClusterType.getByDescription(type);
if (clusterType == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "type=" + type);
return;
}
clusterCreate.setType(clusterType);
} else if (specFilePath == null) {
// create Hadoop (HDFS + MapReduce) cluster as default
clusterCreate.setType(ClusterType.HDFS_MAPRED);
}
if (topology != null) {
try {
clusterCreate.setTopologyPolicy(TopologyType.valueOf(topology));
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "topologyType=" + topology);
return;
}
} else {
clusterCreate.setTopologyPolicy(TopologyType.NONE);
}
try {
if (distro != null) {
List<String> distroNames = getDistroNames();
if (validName(distro, distroNames)) {
clusterCreate.setDistro(distro);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_DISTRO
+ Constants.PARAM_NOT_SUPPORTED + distroNames);
return;
}
} else {
String defaultDistroName =
clusterCreate.getDefaultDistroName(distroRestClient.getAll());
if (CommandsUtils.isBlank(defaultDistroName)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM__NO_DEFAULT_DISTRO);
return;
} else {
clusterCreate.setDistro(defaultDistroName);
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
DistroRead distroRead = distroRestClient.get(clusterCreate.getDistro());
clusterCreate.setDistroVendor(distroRead.getVendor());
clusterCreate.setDistroVersion(distroRead.getVersion());
if (rpNames != null) {
List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
if (rpNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setRpNames(rpNamesList);
}
}
if (dsNames != null) {
List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
if (dsNamesList.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
return;
} else {
clusterCreate.setDsNames(dsNamesList);
}
}
List<String> failedMsgList = new ArrayList<String>();
List<String> warningMsgList = new ArrayList<String>();
Set<String> allNetworkNames = new HashSet<String>();
try {
if (specFilePath != null) {
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterCreate.setSpecFile(true);
clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
clusterCreate.setConfiguration(clusterSpec.getConfiguration());
validateConfiguration(clusterCreate, skipConfigValidation,
warningMsgList);
clusterCreate.validateNodeGroupNames();
if (!validateHAInfo(clusterCreate.getNodeGroups())) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
return;
}
}
allNetworkNames = getAllNetworkNames();
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
if (allNetworkNames.isEmpty()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CANNOT_FIND_NETWORK);
return;
}
Map<NetTrafficType, List<String>> networkConfig = new HashMap<NetTrafficType, List<String>>();
if (networkName == null) {
if (allNetworkNames.size() == 1) {
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).addAll(allNetworkNames);
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SPECIFIED);
return;
}
} else {
if (!allNetworkNames.contains(networkName)
|| (hdfsNetworkName != null && !allNetworkNames.contains(hdfsNetworkName))
|| (mapredNetworkName != null && !allNetworkNames.contains(mapredNetworkName))) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_CREATE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_NETWORK_NAME
+ Constants.PARAM_NOT_SUPPORTED + allNetworkNames.toString());
return;
}
networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MGT_NETWORK).add(networkName);
if (hdfsNetworkName != null) {
networkConfig.put(NetTrafficType.HDFS_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.HDFS_NETWORK).add(hdfsNetworkName);
}
if (mapredNetworkName != null) {
networkConfig.put(NetTrafficType.MAPRED_NETWORK, new ArrayList<String>());
networkConfig.get(NetTrafficType.MAPRED_NETWORK).add(mapredNetworkName);
}
}
notifyNetsUsage(networkConfig, warningMsgList);
clusterCreate.setNetworkConfig(networkConfig);
clusterCreate.validateCDHVersion(warningMsgList);
// Validate that the specified file is correct json format and proper
// value.
if (specFilePath != null) {
List<String> distroRoles = findDistroRoles(clusterCreate);
if (!clusterCreate.getDistro().equalsIgnoreCase(
com.vmware.bdd.utils.Constants.MAPR_VENDOR)) {
clusterCreate.validateClusterCreate(failedMsgList, warningMsgList,
distroRoles);
} else {
clusterCreate.validateClusterCreateOfMapr(failedMsgList,
distroRoles);
}
}
// give a warning message if both type and specFilePath are specified
if (type != null && specFilePath != null) {
warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT);
}
if (!failedMsgList.isEmpty()) {
showFailedMsg(clusterCreate.getName(), failedMsgList);
return;
}
// rest invocation
try {
if (!CommandsUtils.showWarningMsg(clusterCreate.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.create(clusterCreate);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CREAT);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
CommandsUtils.getExceptionMessage(e));
}
}
/**
* notify user which network Serengeti will pick up for mgt/hdfs/mapred
* @param networkConfig
* @param warningMsgList
*/
private void notifyNetsUsage(Map<NetTrafficType, List<String>> networkConfig,
List<String> warningMsgList) {
if (!networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)) {
return;
}
String mgtNetwork = networkConfig.get(NetTrafficType.MGT_NETWORK).get(0);
String hdfsNetwork = mgtNetwork;
String mapredNetwork = mgtNetwork;
if (networkConfig.containsKey(NetTrafficType.HDFS_NETWORK)
&& !networkConfig.get(NetTrafficType.HDFS_NETWORK).isEmpty()) {
hdfsNetwork = networkConfig.get(NetTrafficType.HDFS_NETWORK).get(0);
}
if (networkConfig.containsKey(NetTrafficType.MAPRED_NETWORK)
&& !networkConfig.get(NetTrafficType.MAPRED_NETWORK).isEmpty()) {
mapredNetwork = networkConfig.get(NetTrafficType.MAPRED_NETWORK).get(0);
}
StringBuffer netsUsage = new StringBuffer().append("Hadoop will use network ")
.append(mgtNetwork).append(" for management, ")
.append(hdfsNetwork).append(" for hdfs traffic, and ")
.append(mapredNetwork).append(" for mapreduce traffic");
warningMsgList.add(netsUsage.toString());
}
private String getPassword() {
String firstPassword = getInputedPassword(Constants.ENTER_PASSWORD);
if (firstPassword == null) {
return null;
}
String secondPassword = getInputedPassword(Constants.CONFIRM_PASSWORD);
if (secondPassword == null) {
return null;
}
if (!firstPassword.equals(secondPassword)) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_CONFIRMATION_FAILED);
return null;
}
return firstPassword;
}
private String getInputedPassword(String promptMsg) {
try {
ConsoleReader reader = new ConsoleReader();
reader.setDefaultPrompt(promptMsg);
String password = "";
password = reader.readLine(Character.valueOf('*'));
if (isValidPassword(password)) {
return password;
} else {
return null;
}
} catch (IOException e) {
return null;
}
}
private boolean isValidPassword(String password) {
if (password.length() < Constants.PASSWORD_MIN_LENGTH
|| password.length() > Constants.PASSWORD_MAX_LENGTH) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, null,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PASSWORD_LENGTH_INVALID);
return false;
}
return true;
}
private List<String> findDistroRoles(ClusterCreate clusterCreate) {
DistroRead distroRead = null;
distroRead =
distroRestClient
.get(clusterCreate.getDistro() != null ? clusterCreate
.getDistro() : Constants.DEFAULT_DISTRO);
if (distroRead != null) {
return distroRead.getRoles();
} else {
return null;
}
}
@CliCommand(value = "cluster list", help = "Get cluster information")
public void getCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) {
// rest invocation
try {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(detail);
if (clusters != null && clusters.length > 0) {
Arrays.sort(clusters);
prettyOutputClustersInfo(clusters, detail);
}
} else {
ClusterRead cluster = restClient.get(name, detail);
if (cluster != null) {
prettyOutputClusterInfo(cluster, detail);
printSeperator();
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster export", help = "Export cluster specification")
public void exportClusterSpec(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = false, help = "the cluster spec file path") final String fileName) {
// rest invocation
try {
ClusterCreate cluster = restClient.getSpec(name);
if (cluster != null) {
CommandsUtils.prettyJsonOutput(cluster, fileName);
}
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_EXPORT, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster delete", help = "Delete a cluster")
public void deleteCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name) {
// rest invocation
try {
restClient.delete(name);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_DELETE);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster start", help = "Start a cluster")
public void startCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings
.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_START);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_START);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_START, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster stop", help = "Stop a cluster")
public void stopCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY, Constants.QUERY_ACTION_STOP);
// rest invocation
try {
restClient.actionOps(clusterName, queryStrings);
CommandsUtils.printCmdSuccess(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_RESULT_STOP);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_NODES_IN_CLUSTER, clusterName,
Constants.OUTPUT_OP_STOP, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
@CliOption(key = { "instanceNum" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The resized number of instances. It should be larger that existing one") final int instanceNum,
@CliOption(key = { "cpuNumPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of vCPU for the nodes in this group") final int cpuNumber,
@CliOption(key = { "memCapacityMbPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of memory size in Mb for the nodes in this group") final long memory) {
if ((instanceNum > 0 && cpuNumber == 0 && memory == 0)
|| (instanceNum == 0 && (cpuNumber > 0 || memory > 0))) {
try {
ClusterRead cluster = restClient.get(name, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name
+ " does not exist.");
return;
}
// disallow scale out zookeeper node group.
List<NodeGroupRead> ngs = cluster.getNodeGroups();
boolean found = false;
for (NodeGroupRead ng : ngs) {
if (ng.getName().equals(nodeGroup)) {
found = true;
if (ng.getRoles() != null
&& ng.getRoles().contains(
HadoopRole.ZOOKEEPER_ROLE.toString())
&& instanceNum > 1) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.ZOOKEEPER_NOT_RESIZE);
return;
}
break;
}
}
if (!found) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup
+ " does not exist.");
return;
}
TaskRead taskRead = null;
if (instanceNum > 0) {
restClient.resize(name, nodeGroup, instanceNum);
} else if (cpuNumber > 0 || memory > 0) {
if (cluster.getStatus().ordinal() != ClusterStatus.RUNNING
.ordinal()) {
CommandsUtils.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Cluster must be in 'RUNNING' state to scale up/down");
return;
}
ResourceScale resScale =
new ResourceScale(name, nodeGroup, cpuNumber, memory);
taskRead = restClient.scale(resScale);
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESULT_RESIZE);
if (taskRead != null) {
System.out.println();
printScaleReport(taskRead, name, nodeGroup);
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
} else {
if (instanceNum > 0 && (cpuNumber > 0 || memory > 0)) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"Can not scale out and scale up/down at the same time, you have to run those commands separately");
} else if (instanceNum == 0 && cpuNumber == 0 && memory == 0) {
CommandsUtils
.printCmdFailure(
Constants.OUTPUT_OBJECT_CLUSTER,
name,
Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL,
"You must specify at least one positive value for instanceNum, cpuNumPerNode, or memCapacityPerNode");
} else {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
name, Constants.OUTPUT_OP_RESIZE,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ (instanceNum < 0 ? " instanceNum=" + instanceNum + "," : "")
+ (cpuNumber < 0 ? " cpuNumPerNode=" + cpuNumber + "," : "")
+ (memory < 0 ? " memCapacityMbPerNode=" + memory : ""));
}
}
}
private void printScaleReport(TaskRead taskRead, String clusterName,
String nodeGroupName) {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
setNodeStatusInfo(failedNodes, nodeGroups);
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
columnNamesWithGetMethodNames.put("IP", Arrays.asList("getIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("CPU", Arrays.asList("getCpuNumber"));
columnNamesWithGetMethodNames.put("MEM(MB)", Arrays.asList("getMemory"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
columnNamesWithGetMethodNames.put("NOTES",
Arrays.asList("getErrorMessage"));
try {
System.out.println("The resized node group: " + nodeGroupName);
System.out
.println("The current resized nodes: " + succeedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The failed resized nodes: " + failedNodes.size());
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
throw new CliRestException(e.getMessage());
}
}
private void setNodeStatusInfo(List<NodeStatus> nodes,
List<NodeGroupRead> nodeGroups) {
for (NodeStatus nodeStatus : nodes) {
NodeRead node = getNodeRead(nodeStatus.getNodeName(), nodeGroups);
if (node != null) {
// only show the management Ip currently
nodeStatus.setIp(node.fetchMgtIp());
nodeStatus.setStatus(node.getStatus());
nodeStatus.setCpuNumber(node.getCpuNumber());
nodeStatus.setMemory(node.getMemory());
}
}
}
@CliCommand(value = "cluster setParam", help = "set cluster parameters")
public void setParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "elasticityMode" }, mandatory = false, help = "The elasticity mode: AUTO, MANUAL") final String elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, help = "The minimum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, help = "The maximum number of compute nodes staying powered on (valid in auto elasticity mode)") final Integer maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, help = "The number of instances powered on (valid in manual elasticity mode)") final Integer targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, help = "The relative disk I/O priorities: HIGH, NORNAL, LOW") final String ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type for elasticity params
if ((elasticityMode != null || minComputeNodeNum != null || maxComputeNodeNum != null || targetComputeNodeNum != null)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
ElasticityMode mode = null;
//validate the input of elasticityMode
if (elasticityMode != null) {
try {
mode = ElasticityMode.valueOf(elasticityMode.toUpperCase());
} catch (IllegalArgumentException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " elasticityMode = " + elasticityMode);
return;
}
}
Boolean enableAuto = null;
if (mode != null) {
enableAuto = (mode == ElasticityMode.AUTO) ? true : false;
}
//validate the input parameters
if (!cluster.validateSetParamParameters(targetComputeNodeNum,
minComputeNodeNum, maxComputeNodeNum, enableAuto)) {
return;
}
//validate the input of ioShares
Priority ioPriority = null;
if (ioShares != null) {
try {
ioPriority = Priority.valueOf(ioShares.toUpperCase());
} catch (IllegalArgumentException ex) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE
+ " " + "ioShares = " + ioShares);
return;
}
}
ElasticityRequestBody requestBody = new ElasticityRequestBody();
requestBody.setEnableAuto(enableAuto);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
} else {
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
} else {
requestBody.setMinComputeNodeNum(minComputeNodeNum);
requestBody.setMaxComputeNodeNum(maxComputeNodeNum);
requestBody.setActiveComputeNodeNum(targetComputeNodeNum);
}
requestBody.setIoPriority(ioPriority);
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_ADJUST);
//print warning for ignored parameters under different mode
if (mode != null) {
if (mode == ElasticityMode.AUTO) {
if (targetComputeNodeNum != null) {
System.out.println("For AUTO scaling mode, targetComputeNodeNum will be ignored.");
}
} else {
if (minComputeNodeNum != null || maxComputeNodeNum != null) {
System.out.println("For MANUAL scaling mode, minComputeNodeNum and maxComputeNodeNum will be ignored.");
}
}
}
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_SET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster resetParam", help = "reset cluster parameters")
public void resetParam(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "all" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset all parameters") final boolean all,
@CliOption(key = { "elasticityMode" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset elasticity mode to MANUAL") final boolean elasticityMode,
@CliOption(key = { "minComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset minComputeNodeNum to -1") final boolean minComputeNodeNum,
@CliOption(key = { "maxComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset maxComputeNodeNum to -1") final boolean maxComputeNodeNum,
@CliOption(key = { "targetComputeNodeNum" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset targetComputeNodeNum to -1(activate all compute nodes)") final boolean targetComputeNodeNum,
@CliOption(key = { "ioShares" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "reset disk I/O priorities to LOW") final boolean ioShares) {
try {
//validate if the cluster exists
ClusterRead cluster = restClient.get(clusterName, false);
if (cluster == null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + clusterName
+ " does not exist.");
return;
}
//validate the node group type
if ((elasticityMode || minComputeNodeNum || maxComputeNodeNum || targetComputeNodeNum)
&& !cluster.validateSetManualElasticity()) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_HAVE_COMPUTE_ONLY_GROUP);
return;
}
// reset Auto Elasticity parameters. The default values are:
// elasticityMode: manual
// targetComputeNodes: -1
// minComputeNodes: -1
// maxComputeNodes: -1
// ioShares: normal
ElasticityRequestBody requestBody = new ElasticityRequestBody();
if (elasticityMode || all) {
requestBody.setEnableAuto(false);
}
if (minComputeNodeNum || all) {
requestBody.setMinComputeNodeNum(-1);
}
if (maxComputeNodeNum || all) {
requestBody.setMaxComputeNodeNum(-1);
}
if (targetComputeNodeNum || all) {
requestBody.setActiveComputeNodeNum(-1);
}
if (ioShares || all) {
requestBody.setIoPriority(Priority.NORMAL);
}
restClient.setParam(cluster, requestBody);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_RESET);
} catch (CliRestException e) {
if (e.getMessage() != null) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESET_PARAM,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
@CliCommand(value = "cluster target", help = "Set or query target cluster to run commands")
public void targetCluster(
@CliOption(key = { "name" }, mandatory = false, help = "The cluster name") final String name,
@CliOption(key = { "info" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show target information") final boolean info) {
ClusterRead cluster = null;
boolean noCluster = false;
try {
if (info) {
if (name != null) {
System.out
.println("Warning: can't specify option --name and --info at the same time");
return;
}
String fsUrl = hadoopConfiguration.get("fs.default.name");
String jtUrl = hadoopConfiguration.get("mapred.job.tracker");
if ((fsUrl == null || fsUrl.length() == 0)
&& (jtUrl == null || jtUrl.length() == 0)) {
System.out
.println("There is no targeted cluster. Run \"cluster target --name\" command first.");
return;
}
if (targetClusterName != null && targetClusterName.length() > 0) {
System.out.println("Cluster : " + targetClusterName);
}
if (fsUrl != null && fsUrl.length() > 0) {
System.out.println("HDFS url : " + fsUrl);
}
if (jtUrl != null && jtUrl.length() > 0) {
System.out.println("Job Tracker url : " + jtUrl);
}
if (hiveServerUrl != null && hiveServerUrl.length() > 0) {
System.out.println("Hive server info: " + hiveServerUrl);
}
} else {
if (name == null) {
ClusterRead[] clusters = restClient.getAll(false);
if (clusters != null && clusters.length > 0) {
cluster = clusters[0];
} else {
noCluster = true;
}
} else {
cluster = restClient.get(name, false);
}
if (cluster == null) {
if (noCluster) {
System.out
.println("There is no available cluster for targeting.");
} else {
System.out.println("Failed to target cluster: The cluster "
+ name + " not found");
}
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
} else {
targetClusterName = cluster.getName();
boolean hasHDFS = false;
boolean hasHiveServer = false;
for (NodeGroupRead nodeGroup : cluster.getNodeGroups()) {
for (String role : nodeGroup.getRoles()) {
if (role.equals("hadoop_namenode")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String nameNodeIP = nodes.get(0).fetchMgtIp();
setNameNode(nameNodeIP);
hasHDFS = true;
} else {
throw new CliRestException("no name node available");
}
}
if (role.equals("hadoop_jobtracker")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String jobTrackerIP = nodes.get(0).fetchMgtIp();
setJobTracker(jobTrackerIP);
} else {
throw new CliRestException(
"no job tracker available");
}
}
if (role.equals("hive_server")) {
List<NodeRead> nodes = nodeGroup.getInstances();
if (nodes != null && nodes.size() > 0) {
String hiveServerIP = nodes.get(0).fetchMgtIp();
setHiveServerAddress(hiveServerIP);
hasHiveServer = true;
} else {
throw new CliRestException(
"no hive server available");
}
}
}
}
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
setFsURL(cluster.getExternalHDFS());
hasHDFS = true;
}
if (!hasHDFS) {
setFsURL("");
}
if (!hasHiveServer) {
this.setHiveServerUrl("");
}
}
}
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_TARGET, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
setFsURL("");
setJobTrackerURL("");
this.setHiveServerUrl("");
}
}
private void setNameNode(String nameNodeAddress) {
String hdfsUrl = "hdfs://" + nameNodeAddress + ":8020";
setFsURL(hdfsUrl);
}
private void setFsURL(String fsURL) {
hadoopConfiguration.set("fs.default.name", fsURL);
}
private void setJobTracker(String jobTrackerAddress) {
String jobTrackerUrl = jobTrackerAddress + ":8021";
setJobTrackerURL(jobTrackerUrl);
}
private void setJobTrackerURL(String jobTrackerUrl) {
hadoopConfiguration.set("mapred.job.tracker", jobTrackerUrl);
}
private void setHiveServerAddress(String hiveServerAddress) {
try {
hiveServerUrl = hiveCommands.config(hiveServerAddress, 10000, null);
} catch (Exception e) {
throw new CliRestException("faild to set hive server address");
}
}
private void setHiveServerUrl(String hiveServerUrl) {
this.hiveServerUrl = hiveServerUrl;
}
@CliCommand(value = "cluster config", help = "Config an existing cluster")
public void configCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
@CliOption(key = { "specFile" }, mandatory = true, help = "The spec file name path") final String specFilePath,
@CliOption(key = { "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
@CliOption(key = { "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes) {
// validate the name
if (name.indexOf("-") != -1) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_CLUSTER
+ Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
return;
}
try {
ClusterRead clusterRead = restClient.get(name, false);
// build ClusterCreate object
ClusterCreate clusterConfig = new ClusterCreate();
clusterConfig.setName(clusterRead.getName());
ClusterCreate clusterSpec =
CommandsUtils.getObjectByJsonString(ClusterCreate.class,
CommandsUtils.dataFromFile(specFilePath));
clusterConfig.setNodeGroups(clusterSpec.getNodeGroups());
clusterConfig.setConfiguration(clusterSpec.getConfiguration());
clusterConfig.setExternalHDFS(clusterSpec.getExternalHDFS());
List<String> warningMsgList = new ArrayList<String>();
validateConfiguration(clusterConfig, skipConfigValidation,
warningMsgList);
// add a confirm message for running job
warningMsgList.add("Warning: "
+ Constants.PARAM_CLUSTER_CONFIG_RUNNING_JOB_WARNING);
if (!CommandsUtils.showWarningMsg(clusterConfig.getName(),
Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CONFIG,
warningMsgList, alwaysAnswerYes)) {
return;
}
restClient.configCluster(clusterConfig);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_CONFIG);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CONFIG, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
return;
}
}
@CliCommand(value = "cluster fix", help = "Fix a cluster failure")
public void fixCluster(
@CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String clusterName,
@CliOption(key = { "disk" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Recover a disk failure") final boolean isDiskFailure,
@CliOption(key = { "parallel" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Whether use parallel way to recovery node or not") final boolean parallel,
@CliOption(key = { "nodeGroup" }, mandatory = false, help = "The node group name which failure belong to") final String nodeGroupName) {
try {
TaskRead taskRead = null;
if (!isDiskFailure) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL,
Constants.PARAM_SHOULD_SPECIFY_DISK);
return;
} else {
FixDiskRequestBody requestBody = new FixDiskRequestBody();
requestBody.setParallel(parallel);
if (!CommandsUtils.isBlank(nodeGroupName)) {
requestBody.setNodeGroupName(nodeGroupName);
}
taskRead = restClient.fixDisk(clusterName, requestBody);
if (taskRead == null) {
return;
}
}
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_RESULT_FIX);
System.out.println();
printClusterFixReport(taskRead, clusterName);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
clusterName, Constants.OUTPUT_OP_FIX,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
return;
}
}
private void printClusterFixReport(TaskRead taskRead, String clusterName)
throws Exception {
ClusterRead cluster = restClient.get(clusterName, true);
List<NodeGroupRead> nodeGroups = cluster.getNodeGroups();
List<NodeStatus> succeedNodes = taskRead.getSucceedNodes();
List<NodeStatus> failedNodes = taskRead.getFailNodes();
setNodeStatusInfo(succeedNodes, nodeGroups);
System.out.println("The fixed nodes: " + succeedNodes.size());
LinkedHashMap<String, List<String>> columnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
columnNamesWithGetMethodNames.put("IP", Arrays.asList("getIp"));
columnNamesWithGetMethodNames.put("NAME", Arrays.asList("getNodeName"));
columnNamesWithGetMethodNames.put("STATUS", Arrays.asList("getStatus"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
succeedNodes.toArray(), Constants.OUTPUT_INDENT);
System.out.println("The recovery-failed nodes: " + failedNodes.size());
setNodeStatusInfo(failedNodes, nodeGroups);
columnNamesWithGetMethodNames.put("Error Message",
Arrays.asList("getErrorMessage"));
CommandsUtils.printInTableFormat(columnNamesWithGetMethodNames,
failedNodes.toArray(), Constants.OUTPUT_INDENT);
}
private NodeRead getNodeRead(String nodeName, List<NodeGroupRead> nodeGroups) {
for (NodeGroupRead nodeGroup : nodeGroups) {
List<NodeRead> nodes = nodeGroup.getInstances();
for (NodeRead node : nodes) {
if (node.getName().equals(nodeName)) {
return node;
}
}
}
return null;
}
private void resumeCreateCluster(final String name) {
Map<String, String> queryStrings = new HashMap<String, String>();
queryStrings.put(Constants.QUERY_ACTION_KEY,
Constants.QUERY_ACTION_RESUME);
try {
restClient.actionOps(name, queryStrings);
CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESULT_RESUME);
} catch (CliRestException e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_RESUME, Constants.OUTPUT_OP_RESULT_FAIL,
e.getMessage());
}
}
private Set<String> getAllNetworkNames() {
Set<String> allNetworks = new HashSet<String>();
NetworkRead[] networks = networkRestClient.getAll(false);
if (networks != null) {
for (NetworkRead network : networks) {
allNetworks.add(network.getName());
}
}
return allNetworks;
}
private List<String> getDistroNames() {
List<String> distroNames = new ArrayList<String>(0);
DistroRead[] distros = distroRestClient.getAll();
if (distros != null) {
for (DistroRead distro : distros)
distroNames.add(distro.getName());
}
return distroNames;
}
private boolean validName(String inputName, List<String> validNames) {
for (String name : validNames) {
if (name.equals(inputName)) {
return true;
}
}
return false;
}
private void prettyOutputDynamicResourceInfo(ClusterRead cluster) {
TopologyType topology = cluster.getTopologyPolicy();
if (topology == null || topology == TopologyType.NONE) {
System.out.printf("cluster name: %s, distro: %s, status: %s",
cluster.getName(), cluster.getDistro(), cluster.getStatus());
} else {
System.out.printf(
"cluster name: %s, distro: %s, topology: %s, status: %s",
cluster.getName(), cluster.getDistro(), topology,
cluster.getStatus());
}
System.out.println();
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
System.out.printf("external HDFS: %s\n", cluster.getExternalHDFS());
}
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RUNNING_NODES,
Arrays.asList("getRunningNodesNum"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IOSHARES,
Arrays.asList("getStorage", "getShares"));
try {
CommandsUtils.printInTableFormat(ngColumnNamesWithGetMethodNames,
nodegroups.toArray(), Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClusterInfo(ClusterRead cluster, boolean detail) {
TopologyType topology = cluster.getTopologyPolicy();
String autoElasticityStatus;
String minComputeNodeNum = cluster.retrieveVhmMinNum();
String maxComputeNodeNum = cluster.retrieveVhmMaxNum();
if (cluster.getAutomationEnable() == null) {
autoElasticityStatus = "N/A";
minComputeNodeNum = "N/A";
maxComputeNodeNum = "N/A";
} else if (cluster.getAutomationEnable()) {
autoElasticityStatus = "Enable";
} else {
autoElasticityStatus = "Disable";
}
printSeperator();
// list cluster level params
LinkedHashMap<String, String> clusterParams =
new LinkedHashMap<String, String>();
clusterParams.put("CLUSTER NAME", cluster.getName());
clusterParams.put("DISTRO", cluster.getDistro());
if (topology != null && topology != TopologyType.NONE) {
clusterParams.put("TOPOLOGY", topology.toString());
}
clusterParams.put("AUTO ELASTIC", autoElasticityStatus);
clusterParams.put("MIN COMPUTE NODES NUM", minComputeNodeNum);
clusterParams.put("MAX COMPUTE NODES NUM", maxComputeNodeNum);
clusterParams.put("IO SHARES", cluster.getIoShares() == null ? ""
: cluster.getIoShares().toString());
clusterParams.put("STATUS", cluster.getStatus() == null ? "" : cluster
.getStatus().toString());
if (cluster.getExternalHDFS() != null
&& !cluster.getExternalHDFS().isEmpty()) {
clusterParams.put("EXTERNAL HDFS", cluster.getExternalHDFS());
}
for (String key : clusterParams.keySet()) {
System.out.printf(Constants.OUTPUT_INDENT + "%-26s:"
+ Constants.OUTPUT_INDENT + "%s\n", key, clusterParams.get(key));
}
System.out.println();
LinkedHashMap<String, List<String>> ngColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
List<NodeGroupRead> nodegroups = cluster.getNodeGroups();
if (nodegroups != null) {
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_GROUP_NAME,
Arrays.asList("getName"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_INSTANCE,
Arrays.asList("getInstanceNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_CPU,
Arrays.asList("getCpuNum"));
ngColumnNamesWithGetMethodNames.put(Constants.FORMAT_TABLE_COLUMN_MEM,
Arrays.asList("getMemCapacityMB"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TYPE,
Arrays.asList("getStorage", "getType"));
ngColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_SIZE,
Arrays.asList("getStorage", "getSizeGB"));
try {
if (detail) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNames =
new LinkedHashMap<String, List<String>>();
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_NODE_NAME,
Arrays.asList("getName"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HOST,
Arrays.asList("getHostName"));
if (topology == TopologyType.RACK_AS_RACK
|| topology == TopologyType.HVE) {
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_RACK,
Arrays.asList("getRack"));
}
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("fetchMgtIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_HDFS_IP, Arrays.asList("fetchHdfsIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_MAPRED_IP, Arrays.asList("fetchMapredIp"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_STATUS,
Arrays.asList("getStatus"));
nColumnNamesWithGetMethodNames.put(
Constants.FORMAT_TABLE_COLUMN_TASK,
Arrays.asList("getAction"));
for (NodeGroupRead nodegroup : nodegroups) {
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames,
new NodeGroupRead[] { nodegroup },
Constants.OUTPUT_INDENT);
List<NodeRead> nodes = nodegroup.getInstances();
if (nodes != null) {
LinkedHashMap<String, List<String>> nColumnNamesWithGetMethodNamesClone =
(LinkedHashMap<String, List<String>>) nColumnNamesWithGetMethodNames.clone();
if (!nodes.isEmpty() &&
(nodes.get(0).getIpConfigs() == null
|| (!nodes.get(0).getIpConfigs().containsKey(NetTrafficType.HDFS_NETWORK)
&& !nodes.get(0).getIpConfigs().containsKey(NetTrafficType.MAPRED_NETWORK)))) {
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_HDFS_IP);
nColumnNamesWithGetMethodNamesClone.remove(Constants.FORMAT_TABLE_COLUMN_MAPRED_IP);
}
System.out.println();
CommandsUtils.printInTableFormat(
nColumnNamesWithGetMethodNamesClone, nodes.toArray(),
new StringBuilder().append(Constants.OUTPUT_INDENT)
.append(Constants.OUTPUT_INDENT).toString());
}
System.out.println();
}
} else
CommandsUtils.printInTableFormat(
ngColumnNamesWithGetMethodNames, nodegroups.toArray(),
Constants.OUTPUT_INDENT);
} catch (Exception e) {
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER,
cluster.getName(), Constants.OUTPUT_OP_LIST,
Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
}
}
}
private void prettyOutputClustersInfo(ClusterRead[] clusters, boolean detail) {
for (ClusterRead cluster : clusters) {
prettyOutputClusterInfo(cluster, detail);
}
printSeperator();
}
private void printSeperator() {
StringBuffer seperator =
new StringBuffer().append(Constants.OUTPUT_INDENT);
for (int i = 0; i < Constants.SEPERATOR_LEN; i++) {
seperator.append("=");
}
System.out.println(seperator.toString());
System.out.println();
}
private void showFailedMsg(String name, List<String> failedMsgList) {
// cluster creation failed message.
StringBuilder failedMsg = new StringBuilder();
failedMsg.append(Constants.INVALID_VALUE);
if (failedMsgList.size() > 1) {
failedMsg.append("s");
}
failedMsg.append(" ");
StringBuilder tmpMsg = new StringBuilder();
for (String msg : failedMsgList) {
tmpMsg.append(msg);
}
failedMsg.append(tmpMsg);
CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, name,
Constants.OUTPUT_OP_CREATE, Constants.OUTPUT_OP_RESULT_FAIL,
failedMsg.toString());
}
private void validateConfiguration(ClusterCreate cluster,
boolean skipConfigValidation, List<String> warningMsgList) {
// validate blacklist
ValidateResult blackListResult = validateBlackList(cluster);
if (blackListResult != null) {
addBlackListWarning(blackListResult, warningMsgList);
}
if (!skipConfigValidation) {
// validate whitelist
ValidateResult whiteListResult = validateWhiteList(cluster);
addWhiteListWarning(cluster.getName(), whiteListResult, warningMsgList);
} else {
cluster.setValidateConfig(false);
}
}
private ValidateResult validateBlackList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.BLACK_LIST);
}
private ValidateResult validateWhiteList(ClusterCreate cluster) {
return validateConfiguration(cluster, ValidationType.WHITE_LIST);
}
/*
* Validate a configuration of the cluster at first. Validate configurations
* of all of node groups then. And merge the failed info which have been
* producted by validation between cluster level and node group level.
*/
private ValidateResult validateConfiguration(ClusterCreate cluster,
ValidationType validationType) {
ValidateResult validateResult = new ValidateResult();
// validate cluster level Configuration
ValidateResult vr = null;
if (cluster.getConfiguration() != null
&& !cluster.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
cluster.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
validateResult.setFailureNames(vr.getFailureNames());
validateResult.setNoExistFileNames(vr.getNoExistFileNames());
}
}
List<String> failureNames = new LinkedList<String>();
Map<String, List<String>> noExistingFileNamesMap =
new HashMap<String, List<String>>();
failureNames.addAll(validateResult.getFailureNames());
noExistingFileNamesMap.putAll(validateResult.getNoExistFileNames());
// validate nodegroup level Configuration
for (NodeGroupCreate nodeGroup : cluster.getNodeGroups()) {
if (nodeGroup.getConfiguration() != null
&& !nodeGroup.getConfiguration().isEmpty()) {
vr =
AppConfigValidationUtils.validateConfig(validationType,
nodeGroup.getConfiguration());
if (vr.getType() != ValidateResult.Type.VALID) {
validateResult.setType(vr.getType());
// merge failed names between cluster level and node group level.
for (String failureName : vr.getFailureNames()) {
if (!failureNames.contains(failureName)) {
failureNames.add(failureName);
}
}
// merge no existing file names between cluster level and node
// group level
for (Entry<String, List<String>> noExistingFileNames : vr
.getNoExistFileNames().entrySet()) {
String configType = noExistingFileNames.getKey();
if (noExistingFileNamesMap.containsKey(configType)) {
List<String> noExistingFilesTemp =
noExistingFileNames.getValue();
List<String> noExistingFiles =
noExistingFileNamesMap.get(configType);
for (String fileName : noExistingFilesTemp) {
if (!noExistingFiles.contains(fileName)) {
noExistingFiles.add(fileName);
}
}
noExistingFileNamesMap.put(configType, noExistingFiles);
} else {
noExistingFileNamesMap.put(configType,
noExistingFileNames.getValue());
}
}
}
}
}
validateResult.setFailureNames(failureNames);
validateResult.setNoExistFileNames(noExistingFileNamesMap);
return validateResult;
}
private void addWhiteListWarning(final String clusterName,
ValidateResult whiteListResult, List<String> warningMsgList) {
if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_NO_EXIST_FILE_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
}
} else if (whiteListResult.getType() == ValidateResult.Type.WHITE_LIST_INVALID_NAME) {
String noExistingWarningMsg =
getValidateWarningMsg(whiteListResult.getNoExistFileNames());
String failureNameWarningMsg =
getValidateWarningMsg(whiteListResult.getFailureNames(),
Constants.PARAM_CLUSTER_NOT_IN_WHITE_LIST_WARNING);
if (warningMsgList != null) {
warningMsgList.add(noExistingWarningMsg);
warningMsgList.add(failureNameWarningMsg);
}
}
}
private void addBlackListWarning(ValidateResult blackListResult,
List<String> warningList) {
if (blackListResult.getType() == ValidateResult.Type.NAME_IN_BLACK_LIST) {
String warningMsg =
getValidateWarningMsg(blackListResult.getFailureNames(),
Constants.PARAM_CLUSTER_IN_BLACK_LIST_WARNING
+ Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
if (warningList != null) {
warningList.add(warningMsg);
}
}
}
private String getValidateWarningMsg(List<String> failureNames,
String warningMsg) {
StringBuilder warningMsgBuff = new StringBuilder();
if (failureNames != null && !failureNames.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (String failureName : failureNames) {
warningMsgBuff.append(failureName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (failureNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append(warningMsg);
}
return warningMsgBuff.toString();
}
private String getValidateWarningMsg(
Map<String, List<String>> noExistingFilesMap) {
StringBuilder warningMsgBuff = new StringBuilder();
if (noExistingFilesMap != null && !noExistingFilesMap.isEmpty()) {
warningMsgBuff.append("Warning: ");
for (Entry<String, List<String>> noExistingFilesEntry : noExistingFilesMap
.entrySet()) {
List<String> noExistingFileNames = noExistingFilesEntry.getValue();
for (String noExistingFileName : noExistingFileNames) {
warningMsgBuff.append(noExistingFileName).append(", ");
}
warningMsgBuff.delete(warningMsgBuff.length() - 2,
warningMsgBuff.length());
if (noExistingFileNames.size() > 1) {
warningMsgBuff.append(" are ");
} else {
warningMsgBuff.append(" is ");
}
warningMsgBuff.append("not existing in ");
warningMsgBuff.append(noExistingFilesEntry.getKey() + " scope , ");
}
warningMsgBuff.replace(warningMsgBuff.length() - 2,
warningMsgBuff.length(), ". ");
warningMsgBuff.append(Constants.PARAM_CLUSTER_NOT_TAKE_EFFECT);
}
return warningMsgBuff.toString();
}
private boolean validateHAInfo(NodeGroupCreate[] nodeGroups) {
List<String> haFlagList = Arrays.asList("off", "on", "ft");
if (nodeGroups != null) {
for (NodeGroupCreate group : nodeGroups) {
if (!haFlagList.contains(group.getHaFlag().toLowerCase())) {
return false;
}
}
}
return true;
}
}
|
diff --git a/src/togos/minecraft/maprend/texture/ColorExtractor.java b/src/togos/minecraft/maprend/texture/ColorExtractor.java
index 9c504e1..83e99c5 100644
--- a/src/togos/minecraft/maprend/texture/ColorExtractor.java
+++ b/src/togos/minecraft/maprend/texture/ColorExtractor.java
@@ -1,262 +1,270 @@
package togos.minecraft.maprend.texture;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.imageio.ImageIO;
import togos.minecraft.maprend.Color;
public final class ColorExtractor
{
private static final String BLOCKS_SUBDIR = "textures/blocks/";
private static final String DEFAULT_DIR = "data/vanilla/default/";
private static final int DEFAULT_COLOR = 0xFFFF00FF;
private static final int ID_MASK = 0xFFFF;
private static final int DATA_MASK = 0xF;
private static final int ALPHA_CUTOFF = 0x20;
private static String textureDir = null;
private static int parseInt( String s ) {
// Integer.parseInt pukes if the number is too big for a signed integer!
// So use Long.parseLong and cast, instead.
if( s.startsWith( "0x" ) )
return (int) Long.parseLong( s.substring( 2 ), 16 );
return (int) Long.parseLong( s );
}
private static int getAverageColor( String filename ) throws IOException {
BufferedImage image = ImageIO.read( new File( getBlockPath( filename ) ) );
int a = 0, r = 0, g = 0, b = 0;
int nPix = image.getWidth()*image.getHeight();
int aPix = 0;
for( int y = image.getHeight()-1; y>=0; --y ) {
for( int x = image.getWidth()-1; x>=0; --x ) {
int color = image.getRGB( x, y );
int alpha = Color.component( color, 24 );
a += alpha;
if( alpha>ALPHA_CUTOFF ) {
aPix++;
r += Color.component( color, 16 );
g += Color.component( color, 8 );
b += Color.component( color, 0 );
}
}
}
return Color.color( a/nPix, r/aPix, g/aPix, b/aPix );
}
private static int getColorRecursive( String[] args, int index, ColorInfo res ) throws ColorDescriptionException {
if( args.length<=index ) {
throw new IllegalArgumentException();
}
if( args[index].equals( "average" ) ) {
if( args.length<=index+1 ) {
throw new ColorDescriptionException( "Mode average expects an additional argument" );
}
try {
res.color = getAverageColor( args[index+1] );
return index+2;
} catch ( FileNotFoundException e ) {
throw new ColorDescriptionException( "Could not find image"+args[index+1] );
} catch ( IOException e ) {
throw new ColorDescriptionException( "Could not load image"+args[index+1] );
}
} else if( args[index].equals( "fixed" ) ) {
if( args.length<=index+1 ) {
throw new ColorDescriptionException( "Mode fixed expects an additional argument" );
}
res.color = parseInt( args[index+1] );
return index+2;
} else if( args[index].equals( "multiply" ) ) {
if( args.length<=index+1 ) {
throw new ColorDescriptionException( "Mode multiply expects additional arguments" );
}
ColorInfo infoA = new ColorInfo();
int nextIndex = getColorRecursive( args, index+1, infoA );
ColorInfo infoB = new ColorInfo();
nextIndex = getColorRecursive( args, nextIndex, infoB );
res.color = Color.multiplySolid( infoA.color, infoB.color );
res.biomeColor = infoA.biomeColor;
return nextIndex;
} else if( args[index].equals( "biome" ) ) {
if( args.length<=index+1 ) {
throw new ColorDescriptionException( "Mode biome expects an additional arguement" );
}
if( args[index+1].equals( "grass" ) ) {
res.biomeColor = ColorInfo.BIOME_COLOR_GRASS;
} else if( args[index+1].equals( "foliage" ) ) {
res.biomeColor = ColorInfo.BIOME_COLOR_FOLIAGE;
} else if( args[index+1].equals( "water" ) ) {
res.biomeColor = ColorInfo.BIOME_COLOR_WATER;
} else {
res.biomeColor = ColorInfo.BIOME_COLOR_NONE;
}
if( args.length>index+2 ) {
return getColorRecursive( args, index+2, res );
} else {
res.color = 0xFF7F7F7F;
return index+2;
}
}
throw new ColorDescriptionException( "Unrecognized mode "+args[index] );
}
private static ColorInfo getColorFromArgs( String[] args ) throws ColorDescriptionException {
ColorInfo res = new ColorInfo();
getColorRecursive( args, 2, res );
return res;
}
private static String composeLine( int id, int data, int color, int biome, String name ) {
StringBuilder res = new StringBuilder();
res.append( String.format( "0x%04X", id&ID_MASK ) );
if( data>=0 ) {
res.append( String.format( ":0x%01X", data&DATA_MASK ) );
}
res.append( '\t' );
res.append( String.format( "0x%08X", color ) );
if( biome==ColorInfo.BIOME_COLOR_GRASS ) {
res.append( "\tbiome_grass" );
} else if( biome==ColorInfo.BIOME_COLOR_FOLIAGE ) {
res.append( "\tbiome_foliage" );
} else if( biome==ColorInfo.BIOME_COLOR_WATER ) {
res.append( "\tbiome_water" );
}
res.append( "\t# " );
res.append( name );
res.append( '\n' );
return res.toString();
}
private static final String getBlockPath( String filename ) {
return (textureDir==null ? DEFAULT_DIR : textureDir)+BLOCKS_SUBDIR+filename;
}
public static void main( String[] args ) {
if( args.length<2 ) {
System.err.println( "Usage: <input file> <output file> [<texture dir>]" );
return;
}
File infile = new File( args[0] );
if( !infile.exists() ) {
System.err.println( "Input file \""+args[0]+"\"not found!" );
return;
}
if( args.length>=3 ) {
File f = new File( args[2] );
if( f.exists()&&f.isDirectory() ) {
if( args[2].endsWith( "/" ) ) {
textureDir = args[2];
} else {
textureDir = args[2]+"/";
}
} else {
System.out.println( "Warning: custom texture directory not recognized: "+f.getPath() );
}
}
BufferedReader in = null;
BufferedWriter out = null;
try {
in = new BufferedReader( new FileReader( infile ) );
out = new BufferedWriter( new FileWriter( new File( args[1] ) ) );
- out.write( "# This file defines colors for blocks!\n"+"# You can use your own color map using the -color-map <file> argument.\n"+"#\n"+"# The format is block ID, optionally colon and metadata, tab, color, optionally followed by another tab, a pound, and a comment.\n"+"# Tabs are important; don't use spaces or commas!\n"+"#\n"+"# Empty lines and lines starting with # are ignored, too.\n"+"#\n"+"# 'default' must appear before other block ID -> color mappings\n"+"# Any block with an ID not specifically mapped to a color after the default\n"+"# mapping will be colored with the default color.\n\n" );
+ out.write( "# This file defines colors for blocks!\n"+
+ "# You can use your own color map using the -color-map <file> argument.\n"+
+ "#\n"+
+ "# The format is block ID, optionally colon and metadata, tab, color, optionally followed by another tab, a pound, and a comment.\n"+
+ "# Tabs are important; don't use spaces or commas!\n"+"#\n"+"# Empty lines and lines starting with # are ignored, too.\n"+
+ "#\n"+
+ "# 'default' must appear before other block ID -> color mappings\n"+
+ "# Any block with an ID not specifically mapped to a color after the default\n"+
+ "# mapping will be colored with the default color.\n\n" );
out.write( String.format( "default\t0x%08X\n", DEFAULT_COLOR ) );
String line;
int lineNumber = 0;
while ( (line = in.readLine())!=null ) {
lineNumber++;
line = line.trim();
if( line.isEmpty() )
continue;
if( line.startsWith( "#" ) )
continue;
String[] v = line.split( "\t" );
if( v.length<2 ) {
System.err.println( "Illegal line "+lineNumber+": "+line );
continue;
}
if( v.length<3||v[2].startsWith( "#" ) ) {
System.out.println( "Ignoring line "+lineNumber+": "+line );
continue;
}
String[] v2 = v[0].split( ":" );
int id = 0, data = -1;
try {
id = parseInt( v2[0] );
data = v2.length==2 ? parseInt( v2[1] ) : -1;
} catch ( NumberFormatException e ) {
System.err.println( "Error in line "+lineNumber+": "+line+" - "+e.getMessage() );
continue;
}
ColorInfo color = null;
try {
color = getColorFromArgs( v );
} catch ( ColorDescriptionException e ) {
System.out.println( "Error in line "+lineNumber+": "+e.getMessage() );
continue;
}
out.write( composeLine( id, data, color.color, color.biomeColor, v[1] ) );
}
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if( in!=null ) {
try {
in.close();
} catch ( IOException e ) {
}
}
if( out!=null ) {
try {
out.close();
} catch ( IOException e ) {
}
}
}
}
private static class ColorInfo
{
static final int BIOME_COLOR_NONE = 0;
static final int BIOME_COLOR_GRASS = 1;
static final int BIOME_COLOR_FOLIAGE = 2;
static final int BIOME_COLOR_WATER = 3;
int color;
int biomeColor;
}
private static class ColorDescriptionException extends Exception
{
private static final long serialVersionUID = 1L;
ColorDescriptionException(String message) {
super( message );
}
}
}
| true | true | public static void main( String[] args ) {
if( args.length<2 ) {
System.err.println( "Usage: <input file> <output file> [<texture dir>]" );
return;
}
File infile = new File( args[0] );
if( !infile.exists() ) {
System.err.println( "Input file \""+args[0]+"\"not found!" );
return;
}
if( args.length>=3 ) {
File f = new File( args[2] );
if( f.exists()&&f.isDirectory() ) {
if( args[2].endsWith( "/" ) ) {
textureDir = args[2];
} else {
textureDir = args[2]+"/";
}
} else {
System.out.println( "Warning: custom texture directory not recognized: "+f.getPath() );
}
}
BufferedReader in = null;
BufferedWriter out = null;
try {
in = new BufferedReader( new FileReader( infile ) );
out = new BufferedWriter( new FileWriter( new File( args[1] ) ) );
out.write( "# This file defines colors for blocks!\n"+"# You can use your own color map using the -color-map <file> argument.\n"+"#\n"+"# The format is block ID, optionally colon and metadata, tab, color, optionally followed by another tab, a pound, and a comment.\n"+"# Tabs are important; don't use spaces or commas!\n"+"#\n"+"# Empty lines and lines starting with # are ignored, too.\n"+"#\n"+"# 'default' must appear before other block ID -> color mappings\n"+"# Any block with an ID not specifically mapped to a color after the default\n"+"# mapping will be colored with the default color.\n\n" );
out.write( String.format( "default\t0x%08X\n", DEFAULT_COLOR ) );
String line;
int lineNumber = 0;
while ( (line = in.readLine())!=null ) {
lineNumber++;
line = line.trim();
if( line.isEmpty() )
continue;
if( line.startsWith( "#" ) )
continue;
String[] v = line.split( "\t" );
if( v.length<2 ) {
System.err.println( "Illegal line "+lineNumber+": "+line );
continue;
}
if( v.length<3||v[2].startsWith( "#" ) ) {
System.out.println( "Ignoring line "+lineNumber+": "+line );
continue;
}
String[] v2 = v[0].split( ":" );
int id = 0, data = -1;
try {
id = parseInt( v2[0] );
data = v2.length==2 ? parseInt( v2[1] ) : -1;
} catch ( NumberFormatException e ) {
System.err.println( "Error in line "+lineNumber+": "+line+" - "+e.getMessage() );
continue;
}
ColorInfo color = null;
try {
color = getColorFromArgs( v );
} catch ( ColorDescriptionException e ) {
System.out.println( "Error in line "+lineNumber+": "+e.getMessage() );
continue;
}
out.write( composeLine( id, data, color.color, color.biomeColor, v[1] ) );
}
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if( in!=null ) {
try {
in.close();
} catch ( IOException e ) {
}
}
if( out!=null ) {
try {
out.close();
} catch ( IOException e ) {
}
}
}
}
| public static void main( String[] args ) {
if( args.length<2 ) {
System.err.println( "Usage: <input file> <output file> [<texture dir>]" );
return;
}
File infile = new File( args[0] );
if( !infile.exists() ) {
System.err.println( "Input file \""+args[0]+"\"not found!" );
return;
}
if( args.length>=3 ) {
File f = new File( args[2] );
if( f.exists()&&f.isDirectory() ) {
if( args[2].endsWith( "/" ) ) {
textureDir = args[2];
} else {
textureDir = args[2]+"/";
}
} else {
System.out.println( "Warning: custom texture directory not recognized: "+f.getPath() );
}
}
BufferedReader in = null;
BufferedWriter out = null;
try {
in = new BufferedReader( new FileReader( infile ) );
out = new BufferedWriter( new FileWriter( new File( args[1] ) ) );
out.write( "# This file defines colors for blocks!\n"+
"# You can use your own color map using the -color-map <file> argument.\n"+
"#\n"+
"# The format is block ID, optionally colon and metadata, tab, color, optionally followed by another tab, a pound, and a comment.\n"+
"# Tabs are important; don't use spaces or commas!\n"+"#\n"+"# Empty lines and lines starting with # are ignored, too.\n"+
"#\n"+
"# 'default' must appear before other block ID -> color mappings\n"+
"# Any block with an ID not specifically mapped to a color after the default\n"+
"# mapping will be colored with the default color.\n\n" );
out.write( String.format( "default\t0x%08X\n", DEFAULT_COLOR ) );
String line;
int lineNumber = 0;
while ( (line = in.readLine())!=null ) {
lineNumber++;
line = line.trim();
if( line.isEmpty() )
continue;
if( line.startsWith( "#" ) )
continue;
String[] v = line.split( "\t" );
if( v.length<2 ) {
System.err.println( "Illegal line "+lineNumber+": "+line );
continue;
}
if( v.length<3||v[2].startsWith( "#" ) ) {
System.out.println( "Ignoring line "+lineNumber+": "+line );
continue;
}
String[] v2 = v[0].split( ":" );
int id = 0, data = -1;
try {
id = parseInt( v2[0] );
data = v2.length==2 ? parseInt( v2[1] ) : -1;
} catch ( NumberFormatException e ) {
System.err.println( "Error in line "+lineNumber+": "+line+" - "+e.getMessage() );
continue;
}
ColorInfo color = null;
try {
color = getColorFromArgs( v );
} catch ( ColorDescriptionException e ) {
System.out.println( "Error in line "+lineNumber+": "+e.getMessage() );
continue;
}
out.write( composeLine( id, data, color.color, color.biomeColor, v[1] ) );
}
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if( in!=null ) {
try {
in.close();
} catch ( IOException e ) {
}
}
if( out!=null ) {
try {
out.close();
} catch ( IOException e ) {
}
}
}
}
|
diff --git a/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java b/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java
index 080f2c60..23fac81b 100644
--- a/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java
+++ b/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java
@@ -1,3723 +1,3723 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package net.rptools.maptool.client.ui.zone;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TooManyListenersException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.rptools.lib.CodeTimer;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.ImageBorder;
import net.rptools.lib.swing.ImageLabel;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.maptool.client.AppActions;
import net.rptools.maptool.client.AppConstants;
import net.rptools.maptool.client.AppPreferences;
import net.rptools.maptool.client.AppState;
import net.rptools.maptool.client.AppStyle;
import net.rptools.maptool.client.AppUtil;
import net.rptools.maptool.client.MapTool;
import net.rptools.maptool.client.MapToolUtil;
import net.rptools.maptool.client.ScreenPoint;
import net.rptools.maptool.client.TransferableHelper;
import net.rptools.maptool.client.functions.TokenMoveFunctions;
import net.rptools.maptool.client.tool.PointerTool;
import net.rptools.maptool.client.tool.StampTool;
import net.rptools.maptool.client.tool.drawing.FreehandExposeTool;
import net.rptools.maptool.client.tool.drawing.OvalExposeTool;
import net.rptools.maptool.client.tool.drawing.PolygonExposeTool;
import net.rptools.maptool.client.tool.drawing.RectangleExposeTool;
import net.rptools.maptool.client.ui.Scale;
import net.rptools.maptool.client.ui.Tool;
import net.rptools.maptool.client.ui.htmlframe.HTMLFrameFactory;
import net.rptools.maptool.client.ui.token.AbstractTokenOverlay;
import net.rptools.maptool.client.ui.token.BarTokenOverlay;
import net.rptools.maptool.client.ui.token.NewTokenDialog;
import net.rptools.maptool.client.walker.ZoneWalker;
import net.rptools.maptool.model.AbstractPoint;
import net.rptools.maptool.model.Asset;
import net.rptools.maptool.model.AssetManager;
import net.rptools.maptool.model.CellPoint;
import net.rptools.maptool.model.ExposedAreaMetaData;
import net.rptools.maptool.model.GUID;
import net.rptools.maptool.model.Grid;
import net.rptools.maptool.model.GridCapabilities;
import net.rptools.maptool.model.Label;
import net.rptools.maptool.model.LightSource;
import net.rptools.maptool.model.ModelChangeEvent;
import net.rptools.maptool.model.ModelChangeListener;
import net.rptools.maptool.model.Path;
import net.rptools.maptool.model.Player;
import net.rptools.maptool.model.TextMessage;
import net.rptools.maptool.model.Token;
import net.rptools.maptool.model.TokenFootprint;
import net.rptools.maptool.model.Zone;
import net.rptools.maptool.model.ZonePoint;
import net.rptools.maptool.model.drawing.Drawable;
import net.rptools.maptool.model.drawing.DrawableTexturePaint;
import net.rptools.maptool.model.drawing.DrawnElement;
import net.rptools.maptool.model.drawing.Pen;
import net.rptools.maptool.util.GraphicsUtil;
import net.rptools.maptool.util.ImageManager;
import net.rptools.maptool.util.StringUtil;
import net.rptools.maptool.util.TokenUtil;
import org.apache.log4j.Logger;
/**
*/
public class ZoneRenderer extends JComponent implements DropTargetListener, Comparable<Object> {
private static final long serialVersionUID = 3832897780066104884L;
private static final Logger log = Logger.getLogger(ZoneRenderer.class);
public static final int MIN_GRID_SIZE = 10;
private static LightSourceIconOverlay lightSourceIconOverlay = new LightSourceIconOverlay();
protected Zone zone;
private final ZoneView zoneView;
private Scale zoneScale;
private final DrawableRenderer backgroundDrawableRenderer = new PartitionedDrawableRenderer();
private final DrawableRenderer objectDrawableRenderer = new PartitionedDrawableRenderer();
private final DrawableRenderer tokenDrawableRenderer = new PartitionedDrawableRenderer();
private final DrawableRenderer gmDrawableRenderer = new PartitionedDrawableRenderer();
private final List<ZoneOverlay> overlayList = new ArrayList<ZoneOverlay>();
private final Map<Zone.Layer, List<TokenLocation>> tokenLocationMap = new HashMap<Zone.Layer, List<TokenLocation>>();
private Set<GUID> selectedTokenSet = new LinkedHashSet<GUID>();
private final List<Set<GUID>> selectedTokenSetHistory = new ArrayList<Set<GUID>>();
private final List<LabelLocation> labelLocationList = new LinkedList<LabelLocation>();
private Map<Token, Set<Token>> tokenStackMap;
private final Map<GUID, SelectionSet> selectionSetMap = new HashMap<GUID, SelectionSet>();
private final Map<Token, TokenLocation> tokenLocationCache = new HashMap<Token, TokenLocation>();
private final List<TokenLocation> markerLocationList = new ArrayList<TokenLocation>();
private GeneralPath facingArrow;
private final List<Token> showPathList = new ArrayList<Token>();
// Optimizations
private final Map<GUID, BufferedImage> labelRenderingCache = new HashMap<GUID, BufferedImage>();
private final Map<Token, BufferedImage> replacementImageMap = new HashMap<Token, BufferedImage>();
private final Map<Token, BufferedImage> flipImageMap = new HashMap<Token, BufferedImage>();
private Token tokenUnderMouse;
private ScreenPoint pointUnderMouse;
private Zone.Layer activeLayer;
private String loadingProgress;
private boolean isLoaded;
private BufferedImage fogBuffer;
// I don't like this, at all, but it'll work for now, basically keep track of when the fog cache
// needs to be flushed in the case of switching views
private boolean flushFog = true;
private Area exposedFogArea; // In screen space
private BufferedImage miniImage;
private BufferedImage backbuffer;
private boolean drawBackground = true;
private int lastX;
private int lastY;
private BufferedImage cellShape;
private double lastScale;
private Area visibleScreenArea;
private final List<ItemRenderer> itemRenderList = new LinkedList<ItemRenderer>();
private PlayerView lastView;
private Set<GUID> visibleTokenSet;
private CodeTimer timer;
public static enum TokenMoveCompletion {
TRUE, FALSE, OTHER
}
public ZoneRenderer(Zone zone) {
if (zone == null) {
throw new IllegalArgumentException("Zone cannot be null");
}
this.zone = zone;
zone.addModelChangeListener(new ZoneModelChangeListener());
setFocusable(true);
setZoneScale(new Scale());
zoneView = new ZoneView(zone);
// DnD
setTransferHandler(new TransferableHelper());
try {
getDropTarget().addDropTargetListener(this);
} catch (TooManyListenersException e1) {
// Should never happen because the transfer handler fixes this problem.
}
// Focus
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
requestFocusInWindow();
}
@Override
public void mouseExited(MouseEvent e) {
pointUnderMouse = null;
}
@Override
public void mouseEntered(MouseEvent e) {
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
pointUnderMouse = new ScreenPoint(e.getX(), e.getY());
}
});
// fps.start();
}
public void showPath(Token token, boolean show) {
if (show) {
showPathList.add(token);
} else {
showPathList.remove(token);
}
}
public void centerOn(Token token) {
if (token == null) {
return;
}
centerOn(new ZonePoint(token.getX(), token.getY()));
MapTool.getFrame().getToolbox().setSelectedTool(token.isToken() ? PointerTool.class : StampTool.class);
setActiveLayer(token.getLayer());
selectToken(token.getId());
requestFocusInWindow();
}
public ZonePoint getCenterPoint() {
return new ScreenPoint(getSize().width / 2, getSize().height / 2).convertToZone(this);
}
public boolean isPathShowing(Token token) {
return showPathList.contains(token);
}
public void clearShowPaths() {
showPathList.clear();
repaint();
}
public Scale getZoneScale() {
return zoneScale;
}
public void setZoneScale(Scale scale) {
zoneScale = scale;
invalidateCurrentViewCache();
scale.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (Scale.PROPERTY_SCALE.equals(evt.getPropertyName())) {
tokenLocationCache.clear();
flushFog = true;
}
if (Scale.PROPERTY_OFFSET.equals(evt.getPropertyName())) {
// flushFog = true;
}
visibleScreenArea = null;
repaint();
}
});
}
/**
* I _hate_ this method. But couldn't think of a better way to tell the drawable renderer that a new image had
* arrived TODO: FIX THIS ! Perhaps add a new app listener for when new images show up, add the drawable renderer as
* a listener
*/
public void flushDrawableRenderer() {
backgroundDrawableRenderer.flush();
objectDrawableRenderer.flush();
tokenDrawableRenderer.flush();
gmDrawableRenderer.flush();
}
public ScreenPoint getPointUnderMouse() {
return pointUnderMouse;
}
public void setMouseOver(Token token) {
if (tokenUnderMouse == token) {
return;
}
tokenUnderMouse = token;
repaint();
}
@Override
public boolean isOpaque() {
return false;
}
public void addMoveSelectionSet(String playerId, GUID keyToken, Set<GUID> tokenList, boolean clearLocalSelected) {
// I'm not supposed to be moving a token when someone else is already moving it
if (clearLocalSelected) {
for (GUID guid : tokenList) {
selectedTokenSet.remove(guid);
}
}
selectionSetMap.put(keyToken, new SelectionSet(playerId, keyToken, tokenList));
repaint();
}
public boolean hasMoveSelectionSetMoved(GUID keyToken, ZonePoint point) {
SelectionSet set = selectionSetMap.get(keyToken);
if (set == null) {
return false;
}
Token token = zone.getToken(keyToken);
int x = point.x - token.getX();
int y = point.y - token.getY();
return set.offsetX != x || set.offsetY != y;
}
public void updateMoveSelectionSet(GUID keyToken, ZonePoint offset) {
SelectionSet set = selectionSetMap.get(keyToken);
if (set == null) {
return;
}
Token token = zone.getToken(keyToken);
set.setOffset(offset.x - token.getX(), offset.y - token.getY());
repaint();
}
public void toggleMoveSelectionSetWaypoint(GUID keyToken, ZonePoint location) {
SelectionSet set = selectionSetMap.get(keyToken);
if (set == null) {
return;
}
set.toggleWaypoint(location);
repaint();
}
public ZonePoint getLastWaypoint(GUID keyToken) {
SelectionSet set = selectionSetMap.get(keyToken);
if (set == null) {
return null;
}
return set.getLastWaypoint();
}
public void removeMoveSelectionSet(GUID keyToken) {
SelectionSet set = selectionSetMap.remove(keyToken);
if (set == null) {
return;
}
repaint();
}
public void commitMoveSelectionSet(GUID keyTokenId) {
// TODO: Quick hack to handle updating server state
SelectionSet set = selectionSetMap.get(keyTokenId);
removeMoveSelectionSet(keyTokenId);
MapTool.serverCommand().stopTokenMove(getZone().getId(), keyTokenId);
if (set == null) {
return;
}
CodeTimer moveTimer = new CodeTimer("ZoneRenderer.commitMoveSelectionSet");
moveTimer.setEnabled(AppState.isCollectProfilingData() || log.isDebugEnabled());
moveTimer.setThreshold(1);
moveTimer.start("setup");
Token keyToken = zone.getToken(keyTokenId);
CellPoint originPoint = zone.getGrid().convert(new ZonePoint(keyToken.getX(), keyToken.getY()));
Path<? extends AbstractPoint> path = set.getWalker() != null ? set.getWalker().getPath() : set.gridlessPath;
Set<GUID> selectionSet = set.getTokens();
List<GUID> filteredTokens = new ArrayList<GUID>();
BigDecimal tmc = null;
moveTimer.stop("setup");
moveTimer.start("eachtoken");
for (GUID tokenGUID : selectionSet) {
Token token = zone.getToken(tokenGUID);
// If the token has been deleted, the GUID will still be in the set but getToken() will return null.
if (token == null)
continue;
CellPoint tokenCell = zone.getGrid().convert(new ZonePoint(token.getX(), token.getY()));
int cellOffX = originPoint.x - tokenCell.x;
int cellOffY = originPoint.y - tokenCell.y;
token.applyMove(set.getOffsetX(), set.getOffsetY(), path != null ? path.derive(cellOffX, cellOffY) : null);
flush(token);
MapTool.serverCommand().putToken(zone.getId(), token);
zone.putToken(token);
// No longer need this version
replacementImageMap.remove(token);
// Only add certain tokens to the list to process in the move
// Macro function(s).
if (token.isToken() && token.isVisible()) {
filteredTokens.add(tokenGUID);
}
}
moveTimer.stop("eachtoken");
moveTimer.start("onTokenMove");
if (!filteredTokens.isEmpty()) {
// run tokenMoved() for each token in the filtered selection list, canceling if it returns 1.0
for (GUID tokenGUID : filteredTokens) {
Token token = zone.getToken(tokenGUID);
tmc = TokenMoveFunctions.tokenMoved(token, path, filteredTokens);
if (tmc != null && tmc == BigDecimal.ONE) {
denyMovement(token);
}
}
}
moveTimer.stop("onTokenMove");
moveTimer.start("onMultipleTokensMove");
// Multiple tokens, the list of tokens and call onMultipleTokensMove() macro function.
if (filteredTokens != null && filteredTokens.size() > 1) {
tmc = TokenMoveFunctions.multipleTokensMoved(filteredTokens);
// now determine if the macro returned false and if so
// revert each token's move to the last path.
if (tmc != null && tmc == BigDecimal.ONE) {
for (GUID tokenGUID : filteredTokens) {
Token token = zone.getToken(tokenGUID);
denyMovement(token);
}
}
}
moveTimer.stop("onMultipleTokensMove");
moveTimer.start("updateTokenTree");
MapTool.getFrame().updateTokenTree();
moveTimer.stop("updateTokenTree");
if (moveTimer.isEnabled()) {
String results = moveTimer.toString();
MapTool.getProfilingNoteFrame().addText(results);
if (log.isDebugEnabled())
log.debug(results);
moveTimer.clear();
}
}
/**
* @param token
*/
private void denyMovement(final Token token) {
Path<?> path = token.getLastPath();
if (path != null) {
ZonePoint zp = null;
if (path.getCellPath().get(0) instanceof CellPoint) {
zp = zone.getGrid().convert((CellPoint) path.getCellPath().get(0));
} else {
zp = (ZonePoint) path.getCellPath().get(0);
}
// Relocate
token.setX(zp.x);
token.setY(zp.y);
// Do it again to cancel out the last move position
token.setX(zp.x);
token.setY(zp.y);
// No more last path
token.setLastPath(null);
MapTool.serverCommand().putToken(zone.getId(), token);
// Cache clearing
flush(token);
}
}
public boolean isTokenMoving(Token token) {
for (SelectionSet set : selectionSetMap.values()) {
if (set.contains(token)) {
return true;
}
}
return false;
}
protected void setViewOffset(int x, int y) {
zoneScale.setOffset(x, y);
}
public void centerOn(ZonePoint point) {
int x = point.x;
int y = point.y;
x = getSize().width / 2 - (int) (x * getScale()) - 1;
y = getSize().height / 2 - (int) (y * getScale()) - 1;
setViewOffset(x, y);
repaint();
}
public void centerOn(CellPoint point) {
centerOn(zone.getGrid().convert(point));
}
public void flush(Token token) {
tokenLocationCache.remove(token);
flipImageMap.remove(token);
replacementImageMap.remove(token);
labelRenderingCache.remove(token.getId());
// This should be smarter, but whatever
visibleScreenArea = null;
// This could also be smarter
tokenStackMap = null;
flushFog = true;
renderedLightMap = null;
renderedAuraMap = null;
zoneView.flush(token);
}
public ZoneView getZoneView() {
return zoneView;
}
/**
* Clear internal caches and backbuffers
*/
public void flush() {
if (zone.getBackgroundPaint() instanceof DrawableTexturePaint) {
ImageManager.flushImage(((DrawableTexturePaint) zone.getBackgroundPaint()).getAssetId());
}
ImageManager.flushImage(zone.getMapAssetId());
//MCL: I think these should be added, but I'm not sure so I'm not doing it.
// tokenLocationMap.clear();
// tokenLocationCache.clear();
flushDrawableRenderer();
replacementImageMap.clear();
flipImageMap.clear();
fogBuffer = null;
renderedLightMap = null;
renderedAuraMap = null;
isLoaded = false;
}
public void flushLight() {
renderedLightMap = null;
renderedAuraMap = null;
zoneView.flush();
repaint();
}
public void flushFog() {
flushFog = true;
visibleScreenArea = null;
repaint();
}
public Zone getZone() {
return zone;
}
public void addOverlay(ZoneOverlay overlay) {
overlayList.add(overlay);
}
public void removeOverlay(ZoneOverlay overlay) {
overlayList.remove(overlay);
}
public void moveViewBy(int dx, int dy) {
setViewOffset(getViewOffsetX() + dx, getViewOffsetY() + dy);
}
public void zoomReset(int x, int y) {
zoneScale.zoomReset(x, y);
MapTool.getFrame().getZoomStatusBar().update();
}
public void zoomIn(int x, int y) {
zoneScale.zoomIn(x, y);
MapTool.getFrame().getZoomStatusBar().update();
}
public void zoomOut(int x, int y) {
zoneScale.zoomOut(x, y);
MapTool.getFrame().getZoomStatusBar().update();
}
public void setView(int x, int y, double scale) {
setViewOffset(x, y);
zoneScale.setScale(scale);
MapTool.getFrame().getZoomStatusBar().update();
}
public void enforceView(int x, int y, double scale, int gmWidth, int gmHeight) {
int width = getWidth();
int height = getHeight();
// if (((double) width / height) < ((double) gmWidth / gmHeight))
if ((width * gmHeight) < (height * gmWidth)) {
// Our aspect ratio is narrower than server's, so fit to width
scale = scale * width / gmWidth;
} else {
// Our aspect ratio is shorter than server's, so fit to height
scale = scale * height / gmHeight;
}
setScale(scale);
centerOn(new ZonePoint(x, y));
}
public void forcePlayersView() {
ZonePoint zp = new ScreenPoint(getWidth() / 2, getHeight() / 2).convertToZone(this);
MapTool.serverCommand().enforceZoneView(getZone().getId(), zp.x, zp.y, getScale(), getWidth(), getHeight());
}
public void maybeForcePlayersView() {
if (AppState.isPlayerViewLinked() && MapTool.getPlayer().isGM()) {
forcePlayersView();
}
}
public BufferedImage getMiniImage(int size) {
// if (miniImage == null && getTileImage() !=
// ImageManager.UNKNOWN_IMAGE) {
// miniImage = new BufferedImage(size, size, Transparency.OPAQUE);
// Graphics2D g = miniImage.createGraphics();
// g.setPaint(new TexturePaint(getTileImage(), new Rectangle(0, 0,
// miniImage.getWidth(), miniImage.getHeight())));
// g.fillRect(0, 0, size, size);
// g.dispose();
// }
return miniImage;
}
@Override
public void paintComponent(Graphics g) {
if (timer == null)
timer = new CodeTimer("ZoneRenderer.renderZone");
timer.setEnabled(AppState.isCollectProfilingData() || log.isDebugEnabled());
timer.clear();
timer.setThreshold(10);
Graphics2D g2d = (Graphics2D) g;
timer.start("paintComponent:createView");
PlayerView pl = getPlayerView();
timer.stop("paintComponent:createView");
renderZone(g2d, pl);
int noteVPos = 20;
if (!zone.isVisible()) {
GraphicsUtil.drawBoxedString(g2d, "Map not visible to players", getSize().width / 2, noteVPos);
noteVPos += 20;
}
if (AppState.isShowAsPlayer()) {
GraphicsUtil.drawBoxedString(g2d, "Player View", getSize().width / 2, noteVPos);
}
if (timer.isEnabled()) {
String results = timer.toString();
MapTool.getProfilingNoteFrame().addText(results);
if (log.isDebugEnabled())
log.debug(results);
timer.clear();
}
}
public PlayerView getPlayerView() {
Player.Role role = MapTool.getPlayer().getRole();
if (role == Player.Role.GM && AppState.isShowAsPlayer()) {
role = Player.Role.PLAYER;
}
return getPlayerView(role);
}
/**
* The returned {@link PlayerView} contains a list of tokens that includes all selected tokens that this player owns
* and that have their <code>HasSight</code> checkbox enabled.
*
* @param role
* @return
*/
public PlayerView getPlayerView(Player.Role role) {
List<Token> selectedTokens = null;
if (getSelectedTokenSet() != null && !getSelectedTokenSet().isEmpty()) {
selectedTokens = getSelectedTokensList();
for (ListIterator<Token> iter = selectedTokens.listIterator(); iter.hasNext();) {
Token token = iter.next();
if (!token.getHasSight() || !AppUtil.playerOwns(token)) {
iter.remove();
}
}
}
return new PlayerView(role, selectedTokens);
}
public Rectangle fogExtents() {
return zone.getExposedArea().getBounds();
}
/**
* Get a bounding box, in Zone coordinates, of all the elements in the zone. This method was created by copying
* renderZone() and then replacing each bit of rendering with a routine to simply aggregate the extents of the
* object that would have been rendered.
*
* @return a new Rectangle with the bounding box of all the elements in the Zone
*/
public Rectangle zoneExtents(PlayerView view) {
// Can't initialize extents to any set x/y values, because
// we don't know if the actual map contains that x/y.
// So we need a flag to say extents is 'unset', and the best I
// could come up with is checking for 'null' on each loop iteration.
Rectangle extents = null;
// We don't iterate over the layers in the same order as rendering
// because its cleaner to group them by type and the order doesn't matter.
// First background image extents
// TODO: when the background image can be resized, fix this!
if (zone.getMapAssetId() != null) {
extents = new Rectangle(zone.getBoardX(), zone.getBoardY(), ImageManager.getImage(zone.getMapAssetId(), this).getWidth(), ImageManager.getImage(zone.getMapAssetId(), this).getHeight());
}
// next, extents of drawing objects
List<DrawnElement> drawableList = new LinkedList<DrawnElement>();
drawableList.addAll(zone.getBackgroundDrawnElements());
drawableList.addAll(zone.getObjectDrawnElements());
drawableList.addAll(zone.getDrawnElements());
if (view.isGMView()) {
drawableList.addAll(zone.getGMDrawnElements());
}
for (DrawnElement element : drawableList) {
Drawable drawable = element.getDrawable();
Rectangle drawnBounds = new Rectangle(drawable.getBounds());
// Handle pen size
// This slightly over-estimates the size of the pen, but we want to
// make sure to include the anti-aliased edges.
Pen pen = element.getPen();
int penSize = (int) Math.ceil((pen.getThickness() / 2) + 1);
drawnBounds.setBounds(drawnBounds.x - penSize, drawnBounds.y - penSize, drawnBounds.width + (penSize * 2), drawnBounds.height + (penSize * 2));
if (extents == null)
extents = drawnBounds;
else
extents.add(drawnBounds);
}
// now, add the stamps/tokens
// tokens and stamps are the same thing, just treated differently
// This loop structure is a hack: but the getStamps-type methods return unmodifiable lists,
// so we can't concat them, and there are a fixed number of layers, so its not really extensible anyway.
for (int layer = 0; layer < 4; layer++) {
List<Token> stampList = null;
switch (layer) {
case 0:
stampList = zone.getBackgroundStamps();
break; // background layer
case 1:
stampList = zone.getStampTokens();
break; // object layer
case 2:
if (!view.isGMView()) { // hidden layer
continue;
} else {
stampList = zone.getGMStamps();
break;
}
case 3:
stampList = zone.getTokens();
break; // token layer
}
for (Token element : stampList) {
Rectangle drawnBounds = element.getBounds(zone);
if (element.hasFacing()) {
// Get the facing and do a quick fix to make the math easier: -90 is 'unrotated' for some reason
Integer facing = element.getFacing() + 90;
if (facing > 180) {
facing -= 360;
}
// if 90 degrees, just swap w and h
// also swap them if rotated more than 90 (optimization for non-90deg rotations)
if (facing != 0 && facing != 180) {
if (Math.abs(facing) >= 90) {
drawnBounds.setSize(drawnBounds.height, drawnBounds.width); // swapping h and w
}
// if rotated to non-axis direction, assume the worst case 45 deg
// also assumes the rectangle rotates around its center
// This will usually makes the bounds bigger than necessary, but its quick.
// Also, for quickness, we assume its a square token using the larger dimension
// At 45 deg, the bounds of the square will be sqrt(2) bigger, and the UL corner will
// shift by 1/2 of the length.
// The size increase is: (sqrt*(2) - 1) * size ~= 0.42 * size.
if (facing != 0 && facing != 180 && facing != 90 && facing != -90) {
Integer size = Math.max(drawnBounds.width, drawnBounds.height);
Integer x = drawnBounds.x - (int) (0.21 * size);
Integer y = drawnBounds.y - (int) (0.21 * size);
Integer w = drawnBounds.width + (int) (0.42 * size);
Integer h = drawnBounds.height + (int) (0.42 * size);
drawnBounds.setBounds(x, y, w, h);
}
}
}
// TODO: Handle auras here?
if (extents == null)
extents = drawnBounds;
else
extents.add(drawnBounds);
}
}
if (zone.hasFog()) {
if (extents == null)
extents = fogExtents();
else
extents.add(fogExtents());
}
// TODO: What are token templates?
//renderTokenTemplates(g2d, view);
// TODO: Do lights make the area of interest larger?
// see: renderLights(g2d, view);
// TODO: Do auras make the area of interest larger?
// see: renderAuras(g2d, view);
return extents;
}
/**
* This method clears {@link #renderedAuraMap}, {@link #renderedLightMap}, {@link #visibleScreenArea}, and
* {@link #lastView}. It also flushes the {@link #zoneView} and sets the {@link #flushFog} flag so that fog will be
* recalculated.
*/
public void invalidateCurrentViewCache() {
flushFog = true;
renderedLightMap = null;
renderedAuraMap = null;
visibleScreenArea = null;
lastView = null;
if (zoneView != null) {
zoneView.flush();
}
}
/**
* This is the top-level method of the rendering pipeline that coordinates all other calls.
* {@link #paintComponent(Graphics)} calls this method, then adds the two optional strings,
* "Map not visible to players" and "Player View" as appropriate.
*
* @param g2d
* Graphics2D object normally passed in by {@link #paintComponent(Graphics)}
* @param view
* PlayerView object that describes whether the view is a Player or GM view
*/
public void renderZone(Graphics2D g2d, PlayerView view) {
timer.start("setup");
g2d.setFont(AppStyle.labelFont);
Object oldAA = SwingUtil.useAntiAliasing(g2d);
Rectangle viewRect = new Rectangle(getSize().width, getSize().height);
Area viewArea = new Area(viewRect);
// much of the raster code assumes the user clip is set
boolean resetClip = false;
if (g2d.getClipBounds() == null) {
g2d.setClip(0, 0, viewRect.width, viewRect.height);
resetClip = true;
}
// Are we still waiting to show the zone ?
if (isLoading()) {
g2d.setColor(Color.black);
g2d.fillRect(0, 0, viewRect.width, viewRect.height);
GraphicsUtil.drawBoxedString(g2d, loadingProgress, viewRect.width / 2, viewRect.height / 2);
return;
}
if (MapTool.getCampaign().isBeingSerialized()) {
g2d.setColor(Color.black);
g2d.fillRect(0, 0, viewRect.width, viewRect.height);
GraphicsUtil.drawBoxedString(g2d, " Please Wait ", viewRect.width / 2, viewRect.height / 2);
return;
}
if (zone == null) {
return;
}
if (lastView != null && !lastView.equals(view)) {
invalidateCurrentViewCache();
}
lastView = view;
// Clear internal state
tokenLocationMap.clear();
markerLocationList.clear();
itemRenderList.clear();
timer.stop("setup");
// Calculations
timer.start("calcs-1");
AffineTransform af = new AffineTransform();
af.translate(zoneScale.getOffsetX(), zoneScale.getOffsetY());
af.scale(getScale(), getScale());
// @formatter:off
/* This is the new code that doesn't work. See below for newer code that _might_ work. ;-)
if (visibleScreenArea == null && zoneView.isUsingVision()) {
Area a = zoneView.getVisibleArea(view);
if (a != null && !a.isEmpty())
visibleScreenArea = a;
}
exposedFogArea = new Area(zone.getExposedArea());
if (visibleScreenArea != null) {
if (exposedFogArea != null)
exposedFogArea.transform(af);
visibleScreenArea.transform(af);
}
if (exposedFogArea == null || !zone.hasFog()) {
// fully exposed (screen area)
exposedFogArea = new Area(new Rectangle(0, 0, getSize().width, getSize().height));
}
*/
// @formatter:on
if (visibleScreenArea == null && zoneView.isUsingVision()) {
Area a = zoneView.getVisibleArea(view);
if (a != null && !a.isEmpty())
visibleScreenArea = a.createTransformedArea(af);
}
timer.stop("calcs-1");
timer.start("calcs-2");
{
// renderMoveSelectionSet() requires exposedFogArea to be properly set
exposedFogArea = new Area(zone.getExposedArea());
if (exposedFogArea != null && zone.hasFog()) {
if (visibleScreenArea != null && !visibleScreenArea.isEmpty())
exposedFogArea.intersect(visibleScreenArea);
else {
try {
// Try to calculate the inverse transform and apply it.
viewArea.transform(af.createInverse());
// If it works, restrict the exposedFogArea to the resulting rectangle.
exposedFogArea.intersect(viewArea);
} catch (NoninvertibleTransformException nte) {
// If it doesn't work, ignore the intersection and produce an error (should never happen, right?)
nte.printStackTrace();
}
}
exposedFogArea.transform(af);
} else {
exposedFogArea = viewArea;
}
}
timer.stop("calcs-2");
// Rendering pipeline
if (zone.drawBoard()) {
timer.start("board");
renderBoard(g2d, view);
timer.stop("board");
}
if (Zone.Layer.BACKGROUND.isEnabled()) {
List<DrawnElement> drawables = zone.getBackgroundDrawnElements();
if (!drawables.isEmpty()) {
timer.start("drawableBackground");
renderDrawableOverlay(g2d, backgroundDrawableRenderer, view, drawables);
timer.stop("drawableBackground");
}
List<Token> background = zone.getBackgroundStamps();
if (!background.isEmpty()) {
timer.start("tokensBackground");
renderTokens(g2d, background, view);
timer.stop("tokensBackground");
}
}
if (Zone.Layer.OBJECT.isEnabled()) {
// Drawables on the object layer are always below the grid, and...
List<DrawnElement> drawables = zone.getObjectDrawnElements();
if (!drawables.isEmpty()) {
timer.start("drawableObjects");
renderDrawableOverlay(g2d, objectDrawableRenderer, view, drawables);
timer.stop("drawableObjects");
}
}
timer.start("grid");
renderGrid(g2d, view);
timer.stop("grid");
if (Zone.Layer.OBJECT.isEnabled()) {
// ... Images on the object layer are always ABOVE the grid.
List<Token> stamps = zone.getStampTokens();
if (!stamps.isEmpty()) {
timer.start("tokensStamp");
renderTokens(g2d, stamps, view);
timer.stop("tokensStamp");
}
}
if (Zone.Layer.TOKEN.isEnabled()) {
timer.start("lights");
renderLights(g2d, view);
timer.stop("lights");
timer.start("auras");
renderAuras(g2d, view);
timer.stop("auras");
}
/**
* The following sections used to handle rendering of the Hidden (i.e. "GM") layer followed by the Token layer.
* The problem was that we want all drawables to appear below all tokens, and the old configuration performed
* the rendering in the following order:
* <ol>
* <li>Render Hidden-layer tokens
* <li>Render Hidden-layer drawables
* <li>Render Token-layer drawables
* <li>Render Token-layer tokens
* </ol>
* That's fine for players, but clearly wrong if the view is for the GM. We now use:
* <ol>
* <li>Render Token-layer drawables // Player-drawn images shouldn't obscure GM's images?
* <li>Render Hidden-layer drawables // GM could always use "View As Player" if needed?
* <li>Render Hidden-layer tokens
* <li>Render Token-layer tokens
* </ol>
*/
if (Zone.Layer.TOKEN.isEnabled()) {
List<DrawnElement> drawables = zone.getDrawnElements();
if (!drawables.isEmpty()) {
timer.start("drawableTokens");
renderDrawableOverlay(g2d, tokenDrawableRenderer, view, drawables);
timer.stop("drawableTokens");
}
}
if (view.isGMView()) {
if (Zone.Layer.GM.isEnabled()) {
List<DrawnElement> drawables = zone.getGMDrawnElements();
if (!drawables.isEmpty()) {
timer.start("drawableGM");
renderDrawableOverlay(g2d, gmDrawableRenderer, view, drawables);
timer.stop("drawableGM");
}
List<Token> stamps = zone.getGMStamps();
if (!stamps.isEmpty()) {
timer.start("tokensGM");
renderTokens(g2d, stamps, view);
timer.stop("tokensGM");
}
}
}
if (Zone.Layer.TOKEN.isEnabled()) {
List<Token> tokens = zone.getTokens();
if (!tokens.isEmpty()) {
timer.start("tokens");
renderTokens(g2d, tokens, view);
timer.stop("tokens");
}
timer.start("unowned movement");
renderMoveSelectionSets(g2d, view, getUnOwnedMovementSet(view));
timer.stop("unowned movement");
timer.start("owned movement");
renderMoveSelectionSets(g2d, view, getOwnedMovementSet(view));
timer.stop("owned movement");
// Text associated with tokens being moved is added to a list to be drawn after, i.e. on top of, the tokens themselves.
// So if one moving token is on top of another moving token, at least the textual identifiers will be visible.
timer.start("token name/labels");
renderRenderables(g2d);
timer.stop("token name/labels");
}
/**
* FJE It's probably not appropriate for labels to be above everything, including tokens. Above drawables, yes.
* Above tokens, no. (Although in that case labels could be completely obscured. Hm.)
*/
// Drawing labels is slooooow. :(
// Perhaps we should draw the fog first and use hard fog to determine whether labels need to be drawn?
// (This method has it's own 'timer' calls)
renderLabels(g2d, view);
// (This method has it's own 'timer' calls)
if (zone.hasFog())
renderFog(g2d, view);
// if (zone.visionType ...)
if (view.isGMView()) {
timer.start("visionOverlayGM");
renderGMVisionOverlay(g2d, view);
timer.stop("visionOverlayGM");
} else {
timer.start("visionOverlayPlayer");
renderPlayerVisionOverlay(g2d, view);
timer.stop("visionOverlayPlayer");
}
timer.start("overlays");
for (int i = 0; i < overlayList.size(); i++) {
String msg = null;
ZoneOverlay overlay = overlayList.get(i);
if (timer.isEnabled()) {
msg = "overlays:" + overlay.getClass().getSimpleName();
timer.start(msg);
}
overlay.paintOverlay(this, g2d);
if (timer.isEnabled())
timer.stop(msg);
}
timer.stop("overlays");
timer.start("renderCoordinates");
renderCoordinates(g2d, view);
timer.stop("renderCoordinates");
timer.start("lightSourceIconOverlay.paintOverlay");
if (Zone.Layer.TOKEN.isEnabled()) {
if (view.isGMView() && AppState.isShowLightSources()) {
lightSourceIconOverlay.paintOverlay(this, g2d);
}
}
timer.stop("lightSourceIconOverlay.paintOverlay");
// g2d.setColor(Color.red);
// for (AreaMeta meta : getTopologyAreaData().getAreaList()) {
// Area area = new Area(meta.getArea().getBounds()).createTransformedArea(AffineTransform.getScaleInstance(getScale(), getScale()));
// area = area.createTransformedArea(AffineTransform.getTranslateInstance(zoneScale.getOffsetX(), zoneScale.getOffsetY()));
// g2d.draw(area);
// }
SwingUtil.restoreAntiAliasing(g2d, oldAA);
if (resetClip) {
g2d.setClip(null);
}
}
private void delayRendering(ItemRenderer renderer) {
itemRenderList.add(renderer);
}
private void renderRenderables(Graphics2D g) {
for (ItemRenderer renderer : itemRenderList) {
renderer.render(g);
}
}
public CodeTimer getCodeTimer() {
return timer;
}
private Map<Paint, List<Area>> renderedLightMap;
private void renderLights(Graphics2D g, PlayerView view) {
// Setup
timer.start("lights-1");
Graphics2D newG = (Graphics2D) g.create();
if (!view.isGMView() && visibleScreenArea != null) {
Area clip = new Area(g.getClip());
clip.intersect(visibleScreenArea);
newG.setClip(clip);
}
SwingUtil.useAntiAliasing(newG);
timer.stop("lights-1");
timer.start("lights-2");
AffineTransform af = g.getTransform();
af.translate(getViewOffsetX(), getViewOffsetY());
af.scale(getScale(), getScale());
newG.setTransform(af);
newG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, AppPreferences.getLightOverlayOpacity() / 255.0f));
timer.stop("lights-2");
if (renderedLightMap == null) {
timer.start("lights-3");
// Organize
Map<Paint, List<Area>> colorMap = new HashMap<Paint, List<Area>>();
List<DrawableLight> otherLightList = new LinkedList<DrawableLight>();
for (DrawableLight light : zoneView.getDrawableLights()) {
if (light.getType() == LightSource.Type.NORMAL) {
if (zone.getVisionType() == Zone.VisionType.NIGHT && light.getPaint() != null) {
List<Area> areaList = colorMap.get(light.getPaint().getPaint());
if (areaList == null) {
areaList = new ArrayList<Area>();
colorMap.put(light.getPaint().getPaint(), areaList);
}
areaList.add(new Area(light.getArea()));
}
} else {
// I'm not a huge fan of this hard wiring, but I haven't thought of a better way yet, so this'll work fine for now
otherLightList.add(light);
}
}
timer.stop("lights-3");
timer.start("lights-4");
// Combine same colors to avoid ugly overlap
// Avoid combining _all_ of the lights as the area adds are very expensive, just combine those that overlap
for (List<Area> areaList : colorMap.values()) {
List<Area> sourceList = new LinkedList<Area>(areaList);
areaList.clear();
outter: while (sourceList.size() > 0) {
Area area = sourceList.remove(0);
for (ListIterator<Area> iter = sourceList.listIterator(); iter.hasNext();) {
Area currArea = iter.next();
if (currArea.getBounds().intersects(area.getBounds())) {
iter.remove();
area.add(currArea);
sourceList.add(area);
continue outter;
}
}
// If we are here, we didn't find any other area to merge with
areaList.add(area);
}
// Cut out the bright light
if (areaList.size() > 0) {
for (Area area : areaList) {
for (Area brightArea : zoneView.getBrightLights()) {
area.subtract(brightArea);
}
}
}
}
renderedLightMap = new LinkedHashMap<Paint, List<Area>>();
for (Entry<Paint, List<Area>> entry : colorMap.entrySet()) {
renderedLightMap.put(entry.getKey(), entry.getValue());
}
timer.stop("lights-4");
}
// Draw
timer.start("lights-5");
for (Entry<Paint, List<Area>> entry : renderedLightMap.entrySet()) {
newG.setPaint(entry.getKey());
for (Area area : entry.getValue()) {
newG.fill(area);
}
}
timer.stop("lights-5");
newG.dispose();
}
private Map<Paint, Area> renderedAuraMap;
private void renderAuras(Graphics2D g, PlayerView view) {
// Setup
timer.start("auras-1");
Graphics2D newG = (Graphics2D) g.create();
if (!view.isGMView() && visibleScreenArea != null) {
Area clip = new Area(g.getClip());
clip.intersect(visibleScreenArea);
newG.setClip(clip);
}
SwingUtil.useAntiAliasing(newG);
timer.stop("auras-1");
timer.start("auras-2");
AffineTransform af = g.getTransform();
af.translate(getViewOffsetX(), getViewOffsetY());
af.scale(getScale(), getScale());
newG.setTransform(af);
newG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, AppPreferences.getAuraOverlayOpacity() / 255.0f));
timer.stop("auras-2");
if (renderedAuraMap == null) {
// Organize
Map<Paint, List<Area>> colorMap = new HashMap<Paint, List<Area>>();
timer.start("auras-4");
Color paintColor = new Color(255, 255, 255, 150);
for (DrawableLight light : zoneView.getLights(LightSource.Type.AURA)) {
Paint paint = light.getPaint() != null ? light.getPaint().getPaint() : paintColor;
List<Area> list = colorMap.get(paint);
if (list == null) {
list = new LinkedList<Area>();
list.add(new Area(light.getArea()));
colorMap.put(paint, list);
} else {
list.get(0).add(new Area(light.getArea()));
}
}
renderedAuraMap = new LinkedHashMap<Paint, Area>();
for (Entry<Paint, List<Area>> entry : colorMap.entrySet()) {
renderedAuraMap.put(entry.getKey(), entry.getValue().get(0));
}
timer.stop("auras-4");
}
// Draw
timer.start("auras-5");
for (Entry<Paint, Area> entry : renderedAuraMap.entrySet()) {
newG.setPaint(entry.getKey());
newG.fill(entry.getValue());
}
timer.stop("auras-5");
newG.dispose();
}
/**
* This outlines the area visible to the token under the cursor, clipped to the current fog-of-war. This is
* appropriate for the player view, but the GM sees everything.
*/
private void renderPlayerVisionOverlay(Graphics2D g, PlayerView view) {
Graphics2D g2 = (Graphics2D) g.create();
if (zone.hasFog()) {
Area clip = new Area(new Rectangle(getSize().width, getSize().height));
Area viewArea = new Area(exposedFogArea);
List<Token> tokens = view.getTokens();
if (tokens != null && !tokens.isEmpty()) {
for (Token tok : tokens) {
ExposedAreaMetaData exposedMeta = zone.getExposedAreaMetaData(tok.getExposedAreaGUID());
viewArea.add(exposedMeta.getExposedAreaHistory());
}
}
if (!viewArea.isEmpty()) {
clip.intersect(new Area(viewArea.getBounds2D()));
}
// Note: the viewArea doesn't need to be transform()'d because exposedFogArea has been already.
g2.setClip(clip);
}
renderVisionOverlay(g2, view);
g2.dispose();
}
/**
* Render the vision overlay as though the view were the GM.
*/
private void renderGMVisionOverlay(Graphics2D g, PlayerView view) {
renderVisionOverlay(g, view);
}
/**
* This outlines the area visible to the token under the cursor and shades it with the halo color, if there is one.
*/
private void renderVisionOverlay(Graphics2D g, PlayerView view) {
Area currentTokenVisionArea = getVisibleArea(tokenUnderMouse);
if (currentTokenVisionArea == null)
return;
Area combined = new Area(currentTokenVisionArea);
ExposedAreaMetaData meta = zone.getExposedAreaMetaData(tokenUnderMouse.getExposedAreaGUID());
Area tmpArea = new Area(meta.getExposedAreaHistory());
tmpArea.add(zone.getExposedArea());
if (zone.hasFog()) {
if (tmpArea.isEmpty())
return;
combined.intersect(tmpArea);
}
boolean isOwner = AppUtil.playerOwns(tokenUnderMouse);
boolean tokenIsPC = tokenUnderMouse.getType() == Token.Type.PC;
boolean strictOwnership = MapTool.getServerPolicy() == null ? false : MapTool.getServerPolicy().useStrictTokenManagement();
boolean showVisionAndHalo = isOwner || view.isGMView() || (tokenIsPC && !strictOwnership);
// String player = MapTool.getPlayer().getName();
// System.err.print("tokenUnderMouse.ownedBy(" + player + "): " + isOwner);
// System.err.print(", tokenIsPC: " + tokenIsPC);
// System.err.print(", isGMView(): " + view.isGMView());
// System.err.println(", strictOwnership: " + strictOwnership);
/*
* The vision arc and optional halo-filled visible area shouldn't be shown to everyone. If we are in GM view, or
* if we are the owner of the token in question, or if the token is a PC and strict token ownership is off...
* then the vision arc should be displayed.
*/
if (showVisionAndHalo) {
AffineTransform af = new AffineTransform();
af.translate(zoneScale.getOffsetX(), zoneScale.getOffsetY());
af.scale(getScale(), getScale());
Area area = combined.createTransformedArea(af);
g.setClip(this.getBounds());
Object oldAA = SwingUtil.useAntiAliasing(g);
//g.setStroke(new BasicStroke(2));
g.setColor(new Color(255, 255, 255)); // outline around visible area
g.draw(area);
renderHaloArea(g, area);
SwingUtil.restoreAntiAliasing(g, oldAA);
}
}
private void renderHaloArea(Graphics2D g, Area visible) {
boolean useHaloColor = tokenUnderMouse.getHaloColor() != null && AppPreferences.getUseHaloColorOnVisionOverlay();
if (tokenUnderMouse.getVisionOverlayColor() != null || useHaloColor) {
Color visionColor = useHaloColor ? tokenUnderMouse.getHaloColor() : tokenUnderMouse.getVisionOverlayColor();
g.setColor(new Color(visionColor.getRed(), visionColor.getGreen(), visionColor.getBlue(), AppPreferences.getHaloOverlayOpacity()));
g.fill(visible);
}
}
private void renderLabels(Graphics2D g, PlayerView view) {
timer.start("labels-1");
labelLocationList.clear();
for (Label label : zone.getLabels()) {
ZonePoint zp = new ZonePoint(label.getX(), label.getY());
if (!zone.isPointVisible(zp, view)) {
continue;
}
timer.start("labels-1.1");
ScreenPoint sp = ScreenPoint.fromZonePointRnd(this, zp.x, zp.y);
Rectangle bounds = null;
if (label.isShowBackground()) {
bounds = GraphicsUtil.drawBoxedString(g, label.getLabel(), (int) sp.x, (int) sp.y, SwingUtilities.CENTER, GraphicsUtil.GREY_LABEL, label.getForegroundColor());
} else {
FontMetrics fm = g.getFontMetrics();
int strWidth = SwingUtilities.computeStringWidth(fm, label.getLabel());
int x = (int) (sp.x - strWidth / 2);
int y = (int) (sp.y - fm.getAscent());
g.setColor(label.getForegroundColor());
g.drawString(label.getLabel(), x, (int) sp.y);
bounds = new Rectangle(x, y, strWidth, fm.getHeight());
}
labelLocationList.add(new LabelLocation(bounds, label));
timer.stop("labels-1.1");
}
timer.stop("labels-1");
}
// Private cache variables just for renderFog() and no one else. :)
Integer fogX = null;
Integer fogY = null;
private Area renderFog(Graphics2D g, PlayerView view) {
Dimension size = getSize();
Area fogClip = new Area(new Rectangle(0, 0, size.width, size.height));
Area combined = null;
// Optimization for panning
if (!flushFog && fogX != null && fogY != null && (fogX != getViewOffsetX() || fogY != getViewOffsetY())) {
// This optimization does not seem to keep the alpha channel correctly, and sometimes leaves
// lines on some graphics boards, we'll leave it out for now
// if (Math.abs(fogX - getViewOffsetX()) < size.width && Math.abs(fogY - getViewOffsetY()) < size.height) {
// int deltaX = getViewOffsetX() - fogX;
// int deltaY = getViewOffsetY() - fogY;
//
// Graphics2D buffG = fogBuffer.createGraphics();
//
// buffG.setComposite(AlphaComposite.Src);
// buffG.copyArea(0, 0, size.width, size.height, deltaX, deltaY);
// buffG.dispose();
//
// fogClip = new Area();
// if (deltaX < 0) {
// fogClip.add(new Area(new Rectangle(size.width+deltaX, 0, -deltaX, size.height)));
// } else if (deltaX > 0){
// fogClip.add(new Area(new Rectangle(0, 0, deltaX, size.height)));
// }
//
// if (deltaY < 0) {
// fogClip.add(new Area(new Rectangle(0, size.height + deltaY, size.width, -deltaY)));
// } else if (deltaY > 0) {
// fogClip.add(new Area(new Rectangle(0, 0, size.width, deltaY)));
// }
// }
flushFog = true;
}
boolean cacheNotValid = (fogBuffer == null || fogBuffer.getWidth() != size.width || fogBuffer.getHeight() != size.height);
timer.start("renderFog");
if (flushFog || cacheNotValid) {
fogX = getViewOffsetX();
fogY = getViewOffsetY();
boolean newImage = false;
if (cacheNotValid) {
newImage = true;
timer.start("renderFog-allocateBufferedImage");
fogBuffer = new BufferedImage(size.width, size.height, view.isGMView() ? Transparency.TRANSLUCENT : Transparency.BITMASK);
timer.stop("renderFog-allocateBufferedImage");
}
Graphics2D buffG = fogBuffer.createGraphics();
buffG.setClip(fogClip);
SwingUtil.useAntiAliasing(buffG);
// XXX Is this even needed? Immediately below is another call to fillRect() with the same dimensions!
if (!newImage) {
timer.start("renderFog-clearOldImage");
// Composite oldComposite = buffG.getComposite();
buffG.setComposite(AlphaComposite.Clear);
buffG.fillRect(0, 0, size.width, size.height);
// buffG.setComposite(oldComposite);
timer.stop("renderFog-clearOldImage");
}
timer.start("renderFog-fill");
// Fill
double scale = getScale();
buffG.setPaint(zone.getFogPaint().getPaint(fogX, fogY, scale));
buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, view.isGMView() ? .6f : 1f)); // JFJ this fixes the GM exposed area view.
buffG.fillRect(0, 0, size.width, size.height);
timer.stop("renderFog-fill");
// Cut out the exposed area
AffineTransform af = new AffineTransform();
af.translate(fogX, fogY);
af.scale(scale, scale);
buffG.setTransform(af);
// buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, view.isGMView() ? .6f : 1f));
buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
timer.start("renderFog-visibleArea");
Area visibleArea = zoneView.getVisibleArea(view);
timer.stop("renderFog-visibleArea");
String msg = null;
if (timer.isEnabled()) {
List<Token> list = view.getTokens();
msg = "renderFog-combined(" + (list == null ? 0 : list.size()) + ")";
}
timer.start(msg);
combined = zone.getExposedArea(view);
timer.stop(msg);
timer.start("renderFogArea");
Area exposedArea = null;
Area tempArea = new Area();
boolean combinedView = !zoneView.isUsingVision() || MapTool.isPersonalServer() || !MapTool.getServerPolicy().isUseIndividualFOW() || view.isGMView();
if (view.getTokens() != null) {
// if there are tokens selected combine the areas, then, if individual FOW is enabled
// we pass the combined exposed area to build the soft FOW and visible area.
for (Token tok : view.getTokens()) {
ExposedAreaMetaData meta = zone.getExposedAreaMetaData(tok.getExposedAreaGUID());
exposedArea = meta.getExposedAreaHistory();
tempArea.add(new Area(exposedArea));
}
if (combinedView) {
// combined = zone.getExposedArea(view);
buffG.fill(combined);
renderFogArea(buffG, view, combined, visibleArea);
renderFogOutline(buffG, view, combined);
} else {
buffG.fill(tempArea);
renderFogArea(buffG, view, tempArea, visibleArea);
renderFogOutline(buffG, view, tempArea);
}
} else {
// No tokens selected, so if we are using Individual FOW, we build up all the owned tokens
// exposed area's to build the soft FOW.
if (combinedView) {
if (combined.isEmpty()) {
combined = zone.getExposedArea();
}
buffG.fill(combined);
renderFogArea(buffG, view, combined, visibleArea);
renderFogOutline(buffG, view, combined);
} else {
Area myCombined = new Area();
List<Token> myToks = zone.getTokens();
for (Token tok : myToks) {
if (!AppUtil.playerOwns(tok)) {
continue;
}
ExposedAreaMetaData meta = zone.getExposedAreaMetaData(tok.getExposedAreaGUID());
exposedArea = meta.getExposedAreaHistory();
myCombined.add(new Area(exposedArea));
}
buffG.fill(myCombined);
renderFogArea(buffG, view, myCombined, visibleArea);
renderFogOutline(buffG, view, myCombined);
}
}
// renderFogArea(buffG, view, combined, visibleArea);
timer.stop("renderFogArea");
// timer.start("renderFogOutline");
// renderFogOutline(buffG, view, combined);
// timer.stop("renderFogOutline");
buffG.dispose();
flushFog = false;
}
timer.stop("renderFog");
g.drawImage(fogBuffer, 0, 0, this);
return combined;
}
private void renderFogArea(final Graphics2D buffG, final PlayerView view, Area softFog, Area visibleArea) {
if (zoneView.isUsingVision()) {
buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
if (visibleArea != null && !visibleArea.isEmpty()) {
buffG.setColor(new Color(0, 0, 0, AppPreferences.getFogOverlayOpacity()));
// Fill in the exposed area
buffG.fill(softFog);
buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
Shape oldClip = buffG.getClip();
buffG.setClip(softFog);
buffG.fill(visibleArea);
buffG.setClip(oldClip);
} else {
buffG.setColor(new Color(0, 0, 0, 80));
buffG.fill(softFog);
}
} else {
buffG.fill(softFog);
buffG.setClip(softFog);
}
}
private void renderFogOutline(final Graphics2D buffG, PlayerView view, Area softFog) {
// if (false && AppPreferences.getUseSoftFogEdges()) {
// float alpha = view.isGMView() ? AppPreferences.getFogOverlayOpacity() / 255.0f : 1f;
// GraphicsUtil.renderSoftClipping(buffG, softFog, (int) (zone.getGrid().getSize() * getScale() * .25), alpha);
// } else
{
if (visibleScreenArea != null) {
// buffG.setClip(softFog);
buffG.setTransform(new AffineTransform());
buffG.setComposite(AlphaComposite.Src);
buffG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
buffG.setStroke(new BasicStroke(1));
buffG.setColor(Color.BLACK);
buffG.draw(visibleScreenArea);
// buffG.setClip(oldClip);
}
}
}
public Area getVisibleArea(Token token) {
return zoneView.getVisibleArea(token);
}
public boolean isLoading() {
if (isLoaded) {
// We're done, until the cache is cleared
return false;
}
// Get a list of all the assets in the zone
Set<MD5Key> assetSet = zone.getAllAssetIds();
assetSet.remove(null); // remove bad data
// Make sure they are loaded
int downloadCount = 0;
int cacheCount = 0;
boolean loaded = true;
for (MD5Key id : assetSet) {
// Have we gotten the actual data yet ?
Asset asset = AssetManager.getAsset(id);
if (asset == null) {
AssetManager.getAssetAsynchronously(id);
loaded = false;
continue;
}
downloadCount++;
// Have we loaded the image into memory yet ?
Image image = ImageManager.getImage(asset.getId(), this);
if (image == null || image == ImageManager.TRANSFERING_IMAGE) {
loaded = false;
continue;
}
cacheCount++;
}
loadingProgress = String.format(" Loading Map '%s' - %d/%d Loaded %d/%d Cached", zone.getName(), downloadCount, assetSet.size(), cacheCount, assetSet.size());
isLoaded = loaded;
if (isLoaded) {
// Notify the token tree that it should update
MapTool.getFrame().updateTokenTree();
}
return !isLoaded;
}
protected void renderDrawableOverlay(Graphics g, DrawableRenderer renderer, PlayerView view, List<DrawnElement> drawnElements) {
Rectangle viewport = new Rectangle(zoneScale.getOffsetX(), zoneScale.getOffsetY(), getSize().width, getSize().height);
List<DrawnElement> list = new ArrayList<DrawnElement>();
list.addAll(drawnElements);
renderer.renderDrawables(g, list, viewport, getScale());
}
protected void renderBoard(Graphics2D g, PlayerView view) {
Dimension size = getSize();
if (backbuffer == null || backbuffer.getWidth() != size.width || backbuffer.getHeight() != size.height) {
backbuffer = new BufferedImage(size.width, size.height, Transparency.OPAQUE);
drawBackground = true;
}
Scale scale = getZoneScale();
if (scale.getOffsetX() != lastX || scale.getOffsetY() != lastY || scale.getScale() != lastScale) {
drawBackground = true;
}
if (zone.isBoardChanged()) {
drawBackground = true;
zone.setBoardChanged(false);
}
if (drawBackground) {
Graphics2D bbg = backbuffer.createGraphics();
// Background texture
Paint paint = zone.getBackgroundPaint().getPaint(getViewOffsetX(), getViewOffsetY(), getScale(), this);
bbg.setPaint(paint);
bbg.fillRect(0, 0, size.width, size.height);
// Map
if (zone.getMapAssetId() != null) {
BufferedImage mapImage = ImageManager.getImage(zone.getMapAssetId(), this);
double scaleFactor = getScale();
bbg.drawImage(mapImage, getViewOffsetX() + (int) (zone.getBoardX() * scaleFactor), getViewOffsetY() + (int) (zone.getBoardY() * scaleFactor),
(int) (mapImage.getWidth() * scaleFactor), (int) (mapImage.getHeight() * scaleFactor), null);
}
bbg.dispose();
drawBackground = false;
}
lastX = scale.getOffsetX();
lastY = scale.getOffsetY();
lastScale = scale.getScale();
g.drawImage(backbuffer, 0, 0, this);
}
protected void renderGrid(Graphics2D g, PlayerView view) {
int gridSize = (int) (zone.getGrid().getSize() * getScale());
if (!AppState.isShowGrid() || gridSize < MIN_GRID_SIZE) {
return;
}
zone.getGrid().draw(this, g, g.getClipBounds());
}
protected void renderCoordinates(Graphics2D g, PlayerView view) {
if (AppState.isShowCoordinates()) {
zone.getGrid().drawCoordinatesOverlay(g, this);
}
}
private Set<SelectionSet> getOwnedMovementSet(PlayerView view) {
Set<SelectionSet> movementSet = new HashSet<SelectionSet>();
for (SelectionSet selection : selectionSetMap.values()) {
if (selection.getPlayerId().equals(MapTool.getPlayer().getName())) {
movementSet.add(selection);
}
}
return movementSet;
}
private Set<SelectionSet> getUnOwnedMovementSet(PlayerView view) {
Set<SelectionSet> movementSet = new HashSet<SelectionSet>();
for (SelectionSet selection : selectionSetMap.values()) {
if (!selection.getPlayerId().equals(MapTool.getPlayer().getName())) {
movementSet.add(selection);
}
}
return movementSet;
}
protected void renderMoveSelectionSets(Graphics2D g, PlayerView view, Set<SelectionSet> movementSet) {
if (selectionSetMap.isEmpty()) {
return;
}
double scale = zoneScale.getScale();
boolean clipInstalled = false;
for (SelectionSet set : movementSet) {
Token keyToken = zone.getToken(set.getKeyToken());
if (keyToken == null) {
// It was removed ?
selectionSetMap.remove(set.getKeyToken());
continue;
}
// Hide the hidden layer
if (keyToken.getLayer() == Zone.Layer.GM && !view.isGMView()) {
continue;
}
ZoneWalker walker = set.getWalker();
for (GUID tokenGUID : set.getTokens()) {
Token token = zone.getToken(tokenGUID);
// Perhaps deleted?
if (token == null)
continue;
// Don't bother if it's not visible
if (!token.isVisible() && !view.isGMView())
continue;
// ... or if it's visible only to the owner and that's not us!
if (token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(token))
continue;
// ... or if it doesn't have an image to display. (Hm, should still show *something*?)
Asset asset = AssetManager.getAsset(token.getImageAssetId());
if (asset == null)
continue;
// OPTIMIZE: combine this with the code in renderTokens()
Rectangle footprintBounds = token.getBounds(zone);
ScreenPoint newScreenPoint = ScreenPoint.fromZonePoint(this, footprintBounds.x + set.getOffsetX(), footprintBounds.y + set.getOffsetY());
BufferedImage image = ImageManager.getImage(token.getImageAssetId());
int scaledWidth = (int) (footprintBounds.width * scale);
int scaledHeight = (int) (footprintBounds.height * scale);
// Tokens are centered on the image center point
int x = (int) (newScreenPoint.x);
int y = (int) (newScreenPoint.y);
// Vision visibility
boolean isOwner = view.isGMView() || set.getPlayerId().equals(MapTool.getPlayer().getName());
if (!view.isGMView() && visibleScreenArea != null && !isOwner) {
// FJE Um, why not just assign the clipping area at the top of the routine?
if (!clipInstalled) {
// Only show the part of the path that is visible
Area visibleArea = new Area(g.getClipBounds());
visibleArea.intersect(visibleScreenArea);
g = (Graphics2D) g.create();
g.setClip(new GeneralPath(visibleArea));
clipInstalled = true;
// System.out.println("Adding Clip: " + MapTool.getPlayer().getName());
}
}
// Show path only on the key token
if (token == keyToken) {
if (!token.isStamp()) {
renderPath(g, walker != null ? walker.getPath() : set.gridlessPath, token.getFootprint(zone.getGrid()));
}
}
// handle flipping
BufferedImage workImage = image;
if (token.isFlippedX() || token.isFlippedY()) {
workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency());
int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1);
int workH = image.getHeight() * (token.isFlippedY() ? -1 : 1);
int workX = token.isFlippedX() ? image.getWidth() : 0;
int workY = token.isFlippedY() ? image.getHeight() : 0;
Graphics2D wig = workImage.createGraphics();
wig.drawImage(image, workX, workY, workW, workH, null);
wig.dispose();
}
// Draw token
Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight());
SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height);
int offsetx = 0;
int offsety = 0;
if (token.isSnapToScale()) {
offsetx = (int) (imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width) / 2 * getScale() : 0);
offsety = (int) (imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height) / 2 * getScale() : 0);
}
int tx = x + offsetx;
int ty = y + offsety;
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
at.rotate(Math.toRadians(-token.getFacing() - 90), scaledWidth / 2 - token.getAnchor().x * scale - offsetx, scaledHeight / 2 - token.getAnchor().y * scale - offsety); // facing defaults to down, or -90 degrees
}
if (token.isSnapToScale()) {
at.scale((double) imgSize.width / workImage.getWidth(), (double) imgSize.height / workImage.getHeight());
at.scale(getScale(), getScale());
} else {
at.scale((double) scaledWidth / workImage.getWidth(), (double) scaledHeight / workImage.getHeight());
}
g.drawImage(workImage, at, this);
// Other details
if (token == keyToken) {
Rectangle bounds = new Rectangle(tx, ty, imgSize.width, imgSize.height);
bounds.width *= getScale();
bounds.height *= getScale();
Grid grid = zone.getGrid();
boolean checkForFog = MapTool.getServerPolicy().isUseIndividualFOW() && zoneView.isUsingVision();
boolean showLabels = view.isGMView() || set.getPlayerId().equals(MapTool.getPlayer().getName());
if (checkForFog) {
Path<? extends AbstractPoint> path = set.getWalker() != null ? set.getWalker().getPath() : set.gridlessPath;
List<? extends AbstractPoint> thePoints = path.getCellPath();
/*
* now that we have the last point, we can check to see if it's gridless or not. If not
* gridless, get the last point the token was at and see if the token's footprint is inside the
* visible area to show the label.
*/
if (thePoints.isEmpty()) {
showLabels = false;
} else {
AbstractPoint lastPoint = thePoints.get(thePoints.size() - 1);
Rectangle tokenRectangle = null;
if (lastPoint instanceof CellPoint) {
tokenRectangle = token.getFootprint(grid).getBounds(grid, (CellPoint) lastPoint);
} else {
Rectangle tokBounds = token.getBounds(zone);
tokenRectangle = new Rectangle();
tokenRectangle.setBounds(lastPoint.x, lastPoint.y, (int) tokBounds.getWidth(), (int) tokBounds.getHeight());
}
showLabels = showLabels || zoneView.getVisibleArea(view).intersects(tokenRectangle);
}
} else { // !isUseIndividualFOW()
boolean hasFog = zone.hasFog();
boolean fogIntersects = exposedFogArea.intersects(bounds);
showLabels = showLabels || (visibleScreenArea == null && !hasFog); // no vision - fog
showLabels = showLabels || (visibleScreenArea == null && hasFog && fogIntersects); // no vision + fog
showLabels = showLabels || (visibleScreenArea != null && visibleScreenArea.intersects(bounds) && fogIntersects); // vision
}
if (showLabels) {
// if the token is visible on the screen it will be in the location cache
if (tokenLocationCache.containsKey(token)) {
y += 10 + scaledHeight;
x += scaledWidth / 2;
if (!token.isStamp()) {
if (AppState.getShowMovementMeasurements()) {
String distance = "";
if (walker != null) { // This wouldn't be true unless token.isSnapToGrid() && grid.isPathingSupported()
int distanceTraveled = walker.getDistance();
if (distanceTraveled >= 1) {
distance = Integer.toString(distanceTraveled);
}
} else {
double c = 0;
ZonePoint lastPoint = null;
for (ZonePoint zp : set.gridlessPath.getCellPath()) {
if (lastPoint == null) {
lastPoint = zp;
continue;
}
int a = lastPoint.x - zp.x;
int b = lastPoint.y - zp.y;
c += Math.hypot(a, b);
lastPoint = zp;
}
c /= zone.getGrid().getSize(); // Number of "cells"
c *= zone.getUnitsPerCell(); // "actual" distance traveled
distance = String.format("%.1f", c);
}
if (distance.length() > 0) {
delayRendering(new LabelRenderer(distance, x, y));
y += 20;
}
}
}
if (set.getPlayerId() != null && set.getPlayerId().length() >= 1) {
delayRendering(new LabelRenderer(set.getPlayerId(), x, y));
}
} // !token.isStamp()
} // showLabels
} // token == keyToken
}
}
}
@SuppressWarnings("unchecked")
public void renderPath(Graphics2D g, Path path, TokenFootprint footprint) {
Object oldRendering = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (path.getCellPath().size() == 0) {
return;
}
Grid grid = zone.getGrid();
double scale = getScale();
Rectangle footprintBounds = footprint.getBounds(grid);
if (path.getCellPath().get(0) instanceof CellPoint) {
timer.start("renderPath-1");
CellPoint previousPoint = null;
Point previousHalfPoint = null;
List<CellPoint> cellPath = path.getCellPath();
Set<CellPoint> pathSet = new HashSet<CellPoint>();
List<ZonePoint> waypointList = new LinkedList<ZonePoint>();
for (CellPoint p : cellPath) {
pathSet.addAll(footprint.getOccupiedCells(p));
if (path.isWaypoint(p) && previousPoint != null) {
ZonePoint zp = grid.convert(p);
zp.x += footprintBounds.width / 2;
zp.y += footprintBounds.height / 2;
waypointList.add(zp);
}
previousPoint = p;
}
// Don't show the final path point as a waypoint, it's redundant, and ugly
if (waypointList.size() > 0) {
waypointList.remove(waypointList.size() - 1);
}
timer.stop("renderPath-1");
timer.start("renderPath-2");
Dimension cellOffset = zone.getGrid().getCellOffset();
for (CellPoint p : pathSet) {
ZonePoint zp = grid.convert(p);
zp.x += grid.getCellWidth() / 2 + cellOffset.width;
zp.y += grid.getCellHeight() / 2 + cellOffset.height;
highlightCell(g, zp, grid.getCellHighlight(), 1.0f);
}
for (ZonePoint p : waypointList) {
ZonePoint zp = new ZonePoint(p.x + cellOffset.width, p.y + cellOffset.height);
highlightCell(g, zp, AppStyle.cellWaypointImage, .333f);
}
// Line path
if (grid.getCapabilities().isPathLineSupported()) {
ZonePoint lineOffset = new ZonePoint(footprintBounds.x + footprintBounds.width / 2 - grid.getOffsetX(), footprintBounds.y + footprintBounds.height / 2 - grid.getOffsetY());
int xOffset = (int) (lineOffset.x * scale);
int yOffset = (int) (lineOffset.y * scale);
g.setColor(Color.blue);
previousPoint = null;
for (CellPoint p : cellPath) {
if (previousPoint != null) {
ZonePoint ozp = grid.convert(previousPoint);
int ox = ozp.x;
int oy = ozp.y;
ZonePoint dzp = grid.convert(p);
int dx = dzp.x;
int dy = dzp.y;
ScreenPoint origin = ScreenPoint.fromZonePoint(this, ox, oy);
ScreenPoint destination = ScreenPoint.fromZonePoint(this, dx, dy);
int halfx = (int) ((origin.x + destination.x) / 2);
int halfy = (int) ((origin.y + destination.y) / 2);
Point halfPoint = new Point(halfx, halfy);
if (previousHalfPoint != null) {
int x1 = previousHalfPoint.x + xOffset;
int y1 = previousHalfPoint.y + yOffset;
int x2 = (int) origin.x + xOffset;
int y2 = (int) origin.y + yOffset;
int xh = halfPoint.x + xOffset;
int yh = halfPoint.y + yOffset;
QuadCurve2D curve = new QuadCurve2D.Float(x1, y1, x2, y2, xh, yh);
g.draw(curve);
}
previousHalfPoint = halfPoint;
}
previousPoint = p;
}
}
timer.stop("renderPath-2");
} else {
timer.start("renderPath-3");
// Zone point/gridless path
int scaledWidth = (int) (footprintBounds.width * scale);
int scaledHeight = (int) (footprintBounds.height * scale);
// Line
Color highlight = new Color(255, 255, 255, 80);
Stroke highlightStroke = new BasicStroke(9);
Stroke oldStroke = g.getStroke();
Object oldAA = SwingUtil.useAntiAliasing(g);
ScreenPoint lastPoint = null;
List<ZonePoint> pathList = path.getCellPath();
for (ZonePoint zp : pathList) {
if (lastPoint == null) {
lastPoint = ScreenPoint.fromZonePointRnd(this, zp.x + (footprintBounds.width / 2) * footprint.getScale(), zp.y + (footprintBounds.height / 2) * footprint.getScale());
continue;
}
ScreenPoint nextPoint = ScreenPoint.fromZonePoint(this, zp.x + (footprintBounds.width / 2) * footprint.getScale(), zp.y + (footprintBounds.height / 2) * footprint.getScale());
g.setColor(highlight);
g.setStroke(highlightStroke);
g.drawLine((int) lastPoint.x, (int) lastPoint.y, (int) nextPoint.x, (int) nextPoint.y);
g.setStroke(oldStroke);
g.setColor(Color.blue);
g.drawLine((int) lastPoint.x, (int) lastPoint.y, (int) nextPoint.x, (int) nextPoint.y);
lastPoint = nextPoint;
}
SwingUtil.restoreAntiAliasing(g, oldAA);
// Waypoints
boolean originPoint = true;
for (ZonePoint p : pathList) {
// Skip the first point (it's the path origin)
if (originPoint) {
originPoint = false;
continue;
}
// Skip the final point
if (p == pathList.get(pathList.size() - 1)) {
continue;
}
p = new ZonePoint((int) (p.x + (footprintBounds.width / 2) * footprint.getScale()), (int) (p.y + (footprintBounds.height / 2) * footprint.getScale()));
highlightCell(g, p, AppStyle.cellWaypointImage, .333f);
}
timer.stop("renderPath-3");
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldRendering);
}
public void highlightCell(Graphics2D g, ZonePoint point, BufferedImage image, float size) {
Grid grid = zone.getGrid();
double cwidth = grid.getCellWidth() * getScale();
double cheight = grid.getCellHeight() * getScale();
double iwidth = cwidth * size;
double iheight = cheight * size;
ScreenPoint sp = ScreenPoint.fromZonePoint(this, point);
g.drawImage(image, (int) (sp.x - iwidth / 2), (int) (sp.y - iheight / 2), (int) iwidth, (int) iheight, this);
}
/**
* Get a list of tokens currently visible on the screen. The list is ordered by location starting in the top left
* and going to the bottom right.
*
* @return
*/
public List<Token> getTokensOnScreen() {
List<Token> list = new ArrayList<Token>();
// Always assume tokens, for now
List<TokenLocation> tokenLocationListCopy = new ArrayList<TokenLocation>();
tokenLocationListCopy.addAll(getTokenLocations(Zone.Layer.TOKEN));
for (TokenLocation location : tokenLocationListCopy) {
list.add(location.token);
}
// Sort by location on screen, top left to bottom right
Collections.sort(list, new Comparator<Token>() {
public int compare(Token o1, Token o2) {
if (o1.getY() < o2.getY()) {
return -1;
}
if (o1.getY() > o2.getY()) {
return 1;
}
if (o1.getX() < o2.getX()) {
return -1;
}
if (o1.getX() > o2.getX()) {
return 1;
}
return 0;
}
});
return list;
}
public Zone.Layer getActiveLayer() {
return activeLayer != null ? activeLayer : Zone.Layer.TOKEN;
}
public void setActiveLayer(Zone.Layer layer) {
activeLayer = layer;
selectedTokenSet.clear();
repaint();
}
/**
* Get the token locations for the given layer, creates an empty list if there are not locations for the given layer
*/
private List<TokenLocation> getTokenLocations(Zone.Layer layer) {
List<TokenLocation> list = tokenLocationMap.get(layer);
if (list == null) {
list = new LinkedList<TokenLocation>();
tokenLocationMap.put(layer, list);
}
return list;
}
// TODO: I don't like this hardwiring
protected Shape getCircleFacingArrow(int angle, int size) {
int base = (int) (size * .75);
int width = (int) (size * .35);
facingArrow = new GeneralPath();
facingArrow.moveTo(base, -width);
facingArrow.lineTo(size, 0);
facingArrow.lineTo(base, width);
facingArrow.lineTo(base, -width);
GeneralPath gp = (GeneralPath) facingArrow.createTransformedShape(AffineTransform.getRotateInstance(-Math.toRadians(angle)));
return gp.createTransformedShape(AffineTransform.getScaleInstance(getScale(), getScale()));
}
// TODO: I don't like this hardwiring
protected Shape getSquareFacingArrow(int angle, int size) {
int base = (int) (size * .75);
int width = (int) (size * .35);
facingArrow = new GeneralPath();
facingArrow.moveTo(0, 0);
facingArrow.lineTo(-(size - base), -width);
facingArrow.lineTo(-(size - base), width);
facingArrow.lineTo(0, 0);
GeneralPath gp = (GeneralPath) facingArrow.createTransformedShape(AffineTransform.getRotateInstance(-Math.toRadians(angle)));
return gp.createTransformedShape(AffineTransform.getScaleInstance(getScale(), getScale()));
}
protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) {
Graphics2D clippedG = g;
boolean isGMView = view.isGMView(); // speed things up
timer.start("createClip");
if (!isGMView && visibleScreenArea != null && !tokenList.isEmpty() && tokenList.get(0).isToken()) {
clippedG = (Graphics2D) g.create();
Area visibleArea = new Area(g.getClipBounds());
visibleArea.intersect(visibleScreenArea);
clippedG.setClip(new GeneralPath(visibleArea));
}
timer.stop("createClip");
// This is in screen coordinates
Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height);
Rectangle clipBounds = g.getClipBounds();
double scale = zoneScale.getScale();
Set<GUID> tempVisTokens = new HashSet<GUID>();
// calculations
boolean calculateStacks = !tokenList.isEmpty() && !tokenList.get(0).isStamp() && tokenStackMap == null;
if (calculateStacks) {
tokenStackMap = new HashMap<Token, Set<Token>>();
}
List<Token> tokenPostProcessing = new ArrayList<Token>(tokenList.size());
for (Token token : tokenList) {
timer.start("tokenlist-1");
try {
if (token.isStamp() && isTokenMoving(token)) {
continue;
}
// Don't bother if it's not visible
// NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster
// to just draw the tokens and let them be clipped
if (!token.isVisible() && !isGMView) {
continue;
}
if (token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(token)) {
continue;
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1");
}
timer.start("tokenlist-1.1");
TokenLocation location = tokenLocationCache.get(token);
if (location != null && !location.maybeOnscreen(viewport)) {
timer.stop("tokenlist-1.1");
continue;
}
timer.stop("tokenlist-1.1");
timer.start("tokenlist-1a");
Rectangle footprintBounds = token.getBounds(zone);
timer.stop("tokenlist-1a");
timer.start("tokenlist-1b");
BufferedImage image = ImageManager.getImage(token.getImageAssetId(), this);
timer.stop("tokenlist-1b");
timer.start("tokenlist-1c");
double scaledWidth = (footprintBounds.width * scale);
double scaledHeight = (footprintBounds.height * scale);
// if (!token.isStamp()) {
// // Fit inside the grid
// scaledWidth --;
// scaledHeight --;
// }
ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
timer.stop("tokenlist-1c");
timer.start("tokenlist-1d");
// Tokens are centered on the image center point
double x = tokenScreenLocation.x;
double y = tokenScreenLocation.y;
Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight);
Area tokenBounds = new Area(origBounds);
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
double sx = scaledWidth / 2 + x - (token.getAnchor().x * scale);
double sy = scaledHeight / 2 + y - (token.getAnchor().x * scale);
tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), sx, sy)); // facing defaults to down, or -90 degrees
}
timer.stop("tokenlist-1d");
timer.start("tokenlist-1e");
try {
location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight);
tokenLocationCache.put(token, location);
// Too small ?
if (location.scaledHeight < 1 || location.scaledWidth < 1) {
continue;
}
// Vision visibility
if (!isGMView && token.isToken() && zoneView.isUsingVision()) {
if (!GraphicsUtil.intersects(visibleScreenArea, location.bounds)) {
continue;
}
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1e");
}
// Markers
timer.start("renderTokens:Markers");
if (token.isMarker() && canSeeMarker(token)) {
markerLocationList.add(location);
}
timer.stop("renderTokens:Markers");
// Stacking check
if (calculateStacks) {
timer.start("tokenStack");
// System.out.println(token.getName() + " - " + location.boundsCache);
Set<Token> tokenStackSet = null;
for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) {
// Are we covering anyone ?
// System.out.println("\t" + currLocation.token.getName() + " - " + location.boundsCache.contains(currLocation.boundsCache));
if (location.boundsCache.contains(currLocation.boundsCache)) {
if (tokenStackSet == null) {
tokenStackSet = new HashSet<Token>();
tokenStackMap.put(token, tokenStackSet);
tokenStackSet.add(token);
}
tokenStackSet.add(currLocation.token);
if (tokenStackMap.get(currLocation.token) != null) {
tokenStackSet.addAll(tokenStackMap.get(currLocation.token));
tokenStackMap.remove(currLocation.token);
}
}
}
timer.stop("tokenStack");
}
// Keep track of the location on the screen
// Note the order -- the top most token is at the end of the list
timer.start("renderTokens:Locations");
Zone.Layer layer = token.getLayer();
List<TokenLocation> locationList = getTokenLocations(layer);
if (locationList != null) {
locationList.add(location);
}
timer.stop("renderTokens:Locations");
// Add the token to our visible set.
tempVisTokens.add(token.getId());
// Only draw if we're visible
// NOTE: this takes place AFTER resizing the image, that's so that the user
// suffers a pause only once while scaling, and not as new tokens are
// scrolled onto the screen
timer.start("renderTokens:OnscreenCheck");
if (!location.bounds.intersects(clipBounds)) {
timer.stop("renderTokens:OnscreenCheck");
continue;
}
timer.stop("renderTokens:OnscreenCheck");
// Moving ?
timer.start("renderTokens:ShowMovement");
if (isTokenMoving(token)) {
BufferedImage replacementImage = replacementImageMap.get(token);
if (replacementImage == null) {
replacementImage = ImageUtil.rgbToGrayscale(image);
replacementImageMap.put(token, replacementImage);
}
image = replacementImage;
}
timer.stop("renderTokens:ShowMovement");
// Previous path
timer.start("renderTokens:ShowPath");
if (showPathList.contains(token) && token.getLastPath() != null) {
renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid()));
}
timer.stop("renderTokens:ShowPath");
timer.start("tokenlist-4");
// Halo (TOPDOWN, CIRCLE)
if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) {
Stroke oldStroke = clippedG.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
- clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight));
+ clippedG.draw(location.bounds);
clippedG.setStroke(oldStroke);
}
timer.stop("tokenlist-4");
timer.start("tokenlist-5");
// handle flipping
BufferedImage workImage = image;
if (token.isFlippedX() || token.isFlippedY()) {
workImage = flipImageMap.get(token);
if (workImage == null) {
workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency());
int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1);
int workH = image.getHeight() * (token.isFlippedY() ? -1 : 1);
int workX = token.isFlippedX() ? image.getWidth() : 0;
int workY = token.isFlippedY() ? image.getHeight() : 0;
Graphics2D wig = workImage.createGraphics();
wig.drawImage(image, workX, workY, workW, workH, null);
wig.dispose();
flipImageMap.put(token, workImage);
}
}
timer.stop("tokenlist-5");
timer.start("tokenlist-6");
// Position
Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight());
SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height);
int offsetx = 0;
int offsety = 0;
if (token.isSnapToScale()) {
offsetx = (int) (imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width) / 2 * getScale() : 0);
offsety = (int) (imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height) / 2 * getScale() : 0);
}
double tx = location.x + offsetx;
double ty = location.y + offsety;
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
// Rotated
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth / 2 - (token.getAnchor().x * scale) - offsetx, location.scaledHeight / 2 - (token.getAnchor().y * scale)
- offsety);
// facing defaults to down, or -90 degrees
}
// Draw the token
if (token.isSnapToScale()) {
at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight());
at.scale(getScale(), getScale());
} else {
at.scale((scaledWidth) / workImage.getWidth(), (scaledHeight) / workImage.getHeight());
}
timer.stop("tokenlist-6");
timer.start("tokenlist-7");
clippedG.drawImage(workImage, at, this);
timer.stop("tokenlist-7");
timer.start("tokenlist-8");
// Halo (SQUARE)
// XXX Why are square halos drawn separately?!
if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) {
Stroke oldStroke = g.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight));
clippedG.setStroke(oldStroke);
}
// Facing ?
// TODO: Optimize this by doing it once per token per facing
if (token.hasFacing()) {
Token.TokenShape tokenType = token.getShape();
switch (tokenType) {
case CIRCLE:
Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width / 2);
double cx = location.x + location.scaledWidth / 2;
double cy = location.y + location.scaledHeight / 2;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
case SQUARE:
int facing = token.getFacing();
while (facing < 0) {
facing += 360;
} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff
facing %= 360;
arrow = getSquareFacingArrow(facing, footprintBounds.width / 2);
cx = location.x + location.scaledWidth / 2;
cy = location.y + location.scaledHeight / 2;
// Find the edge of the image
// TODO: Man, this is horrible, there's gotta be a better way to do this
double xp = location.scaledWidth / 2;
double yp = location.scaledHeight / 2;
if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) {
xp = (int) (yp / Math.tan(Math.toRadians(facing)));
if (facing > 180) {
xp = -xp;
yp = -yp;
}
} else {
yp = (int) (xp * Math.tan(Math.toRadians(facing)));
if (facing > 90 && facing < 270) {
xp = -xp;
yp = -yp;
}
}
cx += xp;
cy -= yp;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
}
}
timer.stop("tokenlist-8");
timer.start("tokenlist-9");
// Set up the graphics so that the overlay can just be painted.
Graphics2D locg = (Graphics2D) clippedG.create((int) location.x, (int) location.y, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
Rectangle bounds = new Rectangle(0, 0, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
// Check each of the set values
for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) {
Object stateValue = token.getState(state);
AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state);
if (stateValue instanceof AbstractTokenOverlay) {
overlay = (AbstractTokenOverlay) stateValue;
}
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, stateValue);
}
timer.stop("tokenlist-9");
timer.start("tokenlist-10");
for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) {
Object barValue = token.getState(bar);
BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar);
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, barValue);
} // endfor
locg.dispose();
timer.stop("tokenlist-10");
timer.start("tokenlist-11");
// Keep track of which tokens have been drawn so we can perform post-processing on them later
// (such as selection borders and names/labels)
if (getActiveLayer().equals(token.getLayer()))
tokenPostProcessing.add(token);
timer.stop("tokenlist-11");
// DEBUGGING
// ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY()));
// g.setColor(Color.red);
// g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height);
// g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y);
}
timer.start("tokenlist-12");
boolean useIF = MapTool.getServerPolicy().isUseIndividualFOW();
// Selection and labels
for (Token token : tokenPostProcessing) {
TokenLocation location = tokenLocationCache.get(token);
if (location == null)
continue;
Area bounds = location.bounds;
// TODO: This isn't entirely accurate as it doesn't account for the actual text
// to be in the clipping bounds, but I'll fix that later
if (!bounds.getBounds().intersects(clipBounds)) {
continue;
}
Rectangle footprintBounds = token.getBounds(zone);
boolean isSelected = selectedTokenSet.contains(token.getId());
if (isSelected) {
ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
double width = footprintBounds.width * getScale();
double height = footprintBounds.height * getScale();
ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder;
if (highlightCommonMacros.contains(token)) {
selectedBorder = AppStyle.commonMacroBorder;
}
if (!AppUtil.playerOwns(token)) {
selectedBorder = AppStyle.selectedUnownedBorder;
}
if (useIF && !token.isStamp() && zoneView.isUsingVision()) {
Tool tool = MapTool.getFrame().getToolbox().getSelectedTool();
if (tool instanceof RectangleExposeTool // XXX Change to use marker interface such as ExposeTool?
|| tool instanceof OvalExposeTool || tool instanceof FreehandExposeTool || tool instanceof PolygonExposeTool)
selectedBorder = AppConstants.FOW_TOOLS_BORDER;
}
if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp())) {
AffineTransform oldTransform = clippedG.getTransform();
// Rotated
clippedG.translate(sp.x, sp.y);
clippedG.rotate(Math.toRadians(-token.getFacing() - 90), width / 2 - (token.getAnchor().x * scale), height / 2 - (token.getAnchor().y * scale)); // facing defaults to down, or -90 degrees
selectedBorder.paintAround(clippedG, 0, 0, (int) width, (int) height);
clippedG.setTransform(oldTransform);
} else {
selectedBorder.paintAround(clippedG, (int) sp.x, (int) sp.y, (int) width, (int) height);
}
// Remove labels from the cache if the corresponding tokens are deselected
} else if (!AppState.isShowTokenNames() && labelRenderingCache.containsKey(token.getId())) {
labelRenderingCache.remove(token.getId());
}
// Token names and labels
boolean showCurrentTokenLabel = AppState.isShowTokenNames() || token == tokenUnderMouse;
if (showCurrentTokenLabel) {
GUID tokId = token.getId();
int offset = 3; // Keep it from tramping on the token border.
ImageLabel background;
Color foreground;
if (token.isVisible()) {
if (token.getType() == Token.Type.NPC) {
background = GraphicsUtil.BLUE_LABEL;
foreground = Color.WHITE;
} else {
background = GraphicsUtil.GREY_LABEL;
foreground = Color.BLACK;
}
} else {
background = GraphicsUtil.DARK_GREY_LABEL;
foreground = Color.WHITE;
}
String name = token.getName();
if (isGMView && token.getGMName() != null && !StringUtil.isEmpty(token.getGMName())) {
name += " (" + token.getGMName() + ")";
}
if (!view.equals(lastView) || !labelRenderingCache.containsKey(tokId)) {
// if ((lastView != null && !lastView.equals(view)) || !labelRenderingCache.containsKey(tokId)) {
boolean hasLabel = false;
// Calculate image dimensions
FontMetrics fm = g.getFontMetrics();
Font f = g.getFont();
int strWidth = SwingUtilities.computeStringWidth(fm, name);
int width = strWidth + GraphicsUtil.BOX_PADDINGX * 2;
int height = fm.getHeight() + GraphicsUtil.BOX_PADDINGY * 2;
int labelHeight = height;
// If token has a label (in addition to name).
if (token.getLabel() != null && token.getLabel().trim().length() > 0) {
hasLabel = true;
height = height * 2; // Double the image height for two boxed strings.
int labelWidth = SwingUtilities.computeStringWidth(fm, token.getLabel()) + GraphicsUtil.BOX_PADDINGX * 2;
width = (width > labelWidth) ? width : labelWidth;
}
// Set up the image
BufferedImage labelRender = new BufferedImage(width, height, Transparency.TRANSLUCENT);
Graphics2D gLabelRender = labelRender.createGraphics();
gLabelRender.setFont(f); // Match font used in the main graphics context.
gLabelRender.setRenderingHints(g.getRenderingHints()); // Match rendering style.
// Draw name and label to image
if (hasLabel) {
GraphicsUtil.drawBoxedString(gLabelRender, token.getLabel(), width / 2, height - (labelHeight / 2), SwingUtilities.CENTER, background, foreground);
}
GraphicsUtil.drawBoxedString(gLabelRender, name, width / 2, labelHeight / 2, SwingUtilities.CENTER, background, foreground);
// Add image to cache
labelRenderingCache.put(tokId, labelRender);
}
// Create LabelRenderer using cached label.
Rectangle r = bounds.getBounds();
delayRendering(new LabelRenderer(name, r.x + r.width / 2, r.y + r.height + offset, SwingUtilities.CENTER, background, foreground, tokId));
}
}
timer.stop("tokenlist-12");
timer.start("tokenlist-13");
// Stacks
if (!tokenList.isEmpty() && !tokenList.get(0).isStamp()) { // TODO: find a cleaner way to indicate token layer
if (tokenStackMap != null) { // FIXME Needed to prevent NPE but how can it be null?
for (Token token : tokenStackMap.keySet()) {
Area bounds = getTokenBounds(token);
if (bounds == null) {
// token is offscreen
continue;
}
BufferedImage stackImage = AppStyle.stackImage;
clippedG.drawImage(stackImage, bounds.getBounds().x + bounds.getBounds().width - stackImage.getWidth() + 2, bounds.getBounds().y - 2, null);
}
}
}
// Markers
// for (TokenLocation location : getMarkerLocations()) {
// BufferedImage stackImage = AppStyle.markerImage;
// g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null);
// }
if (clippedG != g) {
clippedG.dispose();
}
timer.stop("tokenlist-13");
visibleTokenSet = Collections.unmodifiableSet(tempVisTokens);
}
private boolean canSeeMarker(Token token) {
return MapTool.getPlayer().isGM() || !StringUtil.isEmpty(token.getNotes());
}
public Set<GUID> getSelectedTokenSet() {
return selectedTokenSet;
}
/**
* Convenience method to return a set of tokens filtered by ownership.
*
* @param tokenSet
* the set of GUIDs to filter
*/
public Set<GUID> getOwnedTokens(Set<GUID> tokenSet) {
Set<GUID> ownedTokens = new LinkedHashSet<GUID>();
if (tokenSet != null) {
for (GUID guid : tokenSet) {
if (!AppUtil.playerOwns(zone.getToken(guid))) {
continue;
}
ownedTokens.add(guid);
}
}
return ownedTokens;
}
/**
* A convienence method to get selected tokens ordered by name
*
* @return List<Token>
*/
public List<Token> getSelectedTokensList() {
List<Token> tokenList = new ArrayList<Token>();
for (GUID g : selectedTokenSet) {
if (zone.getToken(g) != null) {
tokenList.add(zone.getToken(g));
}
}
// Commented out to preserve selection order
// Collections.sort(tokenList, Token.NAME_COMPARATOR);
return tokenList;
}
public boolean isTokenSelectable(GUID tokenGUID) {
if (tokenGUID == null) {
return false;
}
Token token = zone.getToken(tokenGUID);
if (token == null) {
return false;
}
if (!zone.isTokenVisible(token)) {
if (AppUtil.playerOwns(token)) {
return true;
}
return false;
}
return true;
}
public void deselectToken(GUID tokenGUID) {
addToSelectionHistory(selectedTokenSet);
selectedTokenSet.remove(tokenGUID);
MapTool.getFrame().resetTokenPanels();
HTMLFrameFactory.selectedListChanged();
// flushFog = true; // could call flushFog() but also clears visibleScreenArea and I don't know if we want that...
repaint();
}
public boolean selectToken(GUID tokenGUID) {
if (!isTokenSelectable(tokenGUID)) {
return false;
}
addToSelectionHistory(selectedTokenSet);
selectedTokenSet.add(tokenGUID);
MapTool.getFrame().resetTokenPanels();
HTMLFrameFactory.selectedListChanged();
// flushFog = true;
repaint();
return true;
}
public void selectTokens(Collection<GUID> tokens) {
for (GUID tokenGUID : tokens) {
if (!isTokenSelectable(tokenGUID)) {
continue;
}
selectedTokenSet.add(tokenGUID);
}
addToSelectionHistory(selectedTokenSet);
repaint();
MapTool.getFrame().resetTokenPanels();
HTMLFrameFactory.selectedListChanged();
}
/**
* Screen space rectangle
*/
public void selectTokens(Rectangle rect) {
List<GUID> selectedList = new LinkedList<GUID>();
for (TokenLocation location : getTokenLocations(getActiveLayer())) {
if (rect.intersects(location.bounds.getBounds())) {
selectedList.add(location.token.getId());
}
}
selectTokens(selectedList);
}
public void clearSelectedTokens() {
addToSelectionHistory(selectedTokenSet);
clearShowPaths();
selectedTokenSet.clear();
MapTool.getFrame().resetTokenPanels();
HTMLFrameFactory.selectedListChanged();
repaint();
}
public void undoSelectToken() {
// System.out.println("num history items: " + selectedTokenSetHistory.size());
/*
* for (Set<GUID> set : selectedTokenSetHistory) { System.out.println("history item"); for (GUID guid : set) {
* System.out.println(zone.getToken(guid).getName()); } }
*/
if (selectedTokenSetHistory.size() > 0) {
selectedTokenSet = selectedTokenSetHistory.remove(0);
// user may have deleted some of the tokens that are contained in the selection history.
// find them and filter them otherwise the selectionSet will have orphaned GUIDs and
// they will cause NPE
Set<GUID> invalidTokenSet = new HashSet<GUID>();
for (GUID guid : selectedTokenSet) {
if (zone.getToken(guid) == null) {
invalidTokenSet.add(guid);
}
}
selectedTokenSet.removeAll(invalidTokenSet);
// if there is no token left in the set, undo again
if (selectedTokenSet.size() == 0) {
undoSelectToken();
}
}
// TODO: if selection history is empty, notify the selection panel to
// disable the undo button.
MapTool.getFrame().resetTokenPanels();
HTMLFrameFactory.selectedListChanged();
repaint();
}
private void addToSelectionHistory(Set<GUID> selectionSet) {
// don't add empty selections to history
if (selectionSet.size() == 0) {
return;
}
Set<GUID> history = new HashSet<GUID>(selectionSet);
selectedTokenSetHistory.add(0, history);
// limit the history to a certain size
if (selectedTokenSetHistory.size() > 20) {
selectedTokenSetHistory.subList(20, selectedTokenSetHistory.size() - 1).clear();
}
}
public void cycleSelectedToken(int direction) {
List<Token> visibleTokens = getTokensOnScreen();
Set<GUID> selectedTokenSet = getSelectedTokenSet();
Integer newSelection = null;
if (visibleTokens.size() == 0) {
return;
}
if (selectedTokenSet.size() == 0) {
newSelection = 0;
} else {
// Find the first selected token on the screen
for (int i = 0; i < visibleTokens.size(); i++) {
Token token = visibleTokens.get(i);
if (!isTokenSelectable(token.getId())) {
continue;
}
if (getSelectedTokenSet().contains(token.getId())) {
newSelection = i;
break;
}
}
// Pick the next
newSelection += direction;
}
if (newSelection < 0) {
newSelection = visibleTokens.size() - 1;
}
if (newSelection >= visibleTokens.size()) {
newSelection = 0;
}
// Make the selection
clearSelectedTokens();
selectToken(visibleTokens.get(newSelection).getId());
}
/**
* Convenience function to check if a player owns all the tokens in the selection set
*
* @return true if every token in selectedTokenSet is owned by the player
*/
public boolean playerOwnsAllSelected() {
if (selectedTokenSet.isEmpty()) {
return false;
}
for (GUID tokenGUID : selectedTokenSet) {
if (!AppUtil.playerOwns(zone.getToken(tokenGUID))) {
return false;
}
}
return true;
}
public Area getTokenBounds(Token token) {
TokenLocation location = tokenLocationCache.get(token);
if (location != null && !location.maybeOnscreen(new Rectangle(0, 0, getSize().width, getSize().height))) {
location = null;
}
return location != null ? location.bounds : null;
}
public Area getMarkerBounds(Token token) {
for (TokenLocation location : markerLocationList) {
if (location.token == token) {
return location.bounds;
}
}
return null;
}
public Rectangle getLabelBounds(Label label) {
for (LabelLocation location : labelLocationList) {
if (location.label == label) {
return location.bounds;
}
}
return null;
}
/**
* Returns the token at screen location x, y (not cell location).
* <p>
* TODO: Add a check so that tokens owned by the current player are given priority.
*
* @param x
* @param y
* @return
*/
public Token getTokenAt(int x, int y) {
List<TokenLocation> locationList = new ArrayList<TokenLocation>();
locationList.addAll(getTokenLocations(getActiveLayer()));
Collections.reverse(locationList);
for (TokenLocation location : locationList) {
if (location.bounds.contains(x, y)) {
return location.token;
}
}
return null;
}
public Token getMarkerAt(int x, int y) {
List<TokenLocation> locationList = new ArrayList<TokenLocation>();
locationList.addAll(markerLocationList);
Collections.reverse(locationList);
for (TokenLocation location : locationList) {
if (location.bounds.contains(x, y)) {
return location.token;
}
}
return null;
}
public List<Token> getTokenStackAt(int x, int y) {
Token token = getTokenAt(x, y);
if (token == null || tokenStackMap == null || !tokenStackMap.containsKey(token)) {
return null;
}
List<Token> tokenList = new ArrayList<Token>(tokenStackMap.get(token));
Collections.sort(tokenList, Token.COMPARE_BY_NAME);
return tokenList;
}
/**
* Returns the label at screen location x, y (not cell location). To get the token at a cell location, use
* getGameMap() and use that.
*
* @param x
* @param y
* @return
*/
public Label getLabelAt(int x, int y) {
List<LabelLocation> labelList = new ArrayList<LabelLocation>();
labelList.addAll(labelLocationList);
Collections.reverse(labelList);
for (LabelLocation location : labelList) {
if (location.bounds.contains(x, y)) {
return location.label;
}
}
return null;
}
public int getViewOffsetX() {
return zoneScale.getOffsetX();
}
public int getViewOffsetY() {
return zoneScale.getOffsetY();
}
public void adjustGridSize(int delta) {
zone.getGrid().setSize(Math.max(0, zone.getGrid().getSize() + delta));
repaint();
}
public void moveGridBy(int dx, int dy) {
int gridOffsetX = zone.getGrid().getOffsetX();
int gridOffsetY = zone.getGrid().getOffsetY();
gridOffsetX += dx;
gridOffsetY += dy;
if (gridOffsetY > 0) {
gridOffsetY = gridOffsetY - (int) zone.getGrid().getCellHeight();
}
if (gridOffsetX > 0) {
gridOffsetX = gridOffsetX - (int) zone.getGrid().getCellWidth();
}
zone.getGrid().setOffset(gridOffsetX, gridOffsetY);
repaint();
}
/**
* Since the map can be scaled, this is a convenience method to find out what cell is at this location.
*
* @param screenPoint
* Find the cell for this point.
* @return The cell coordinates of the passed screen point.
*/
public CellPoint getCellAt(ScreenPoint screenPoint) {
ZonePoint zp = screenPoint.convertToZone(this);
return zone.getGrid().convert(zp);
}
public void setScale(double scale) {
if (zoneScale.getScale() != scale) {
/*
* MCL: I think it is correct to clear these caches (if not more).
*/
tokenLocationCache.clear();
invalidateCurrentViewCache();
zoneScale.zoomScale(getWidth() / 2, getHeight() / 2, scale);
MapTool.getFrame().getZoomStatusBar().update();
}
}
public double getScale() {
return zoneScale.getScale();
}
public double getScaledGridSize() {
// Optimize: only need to calc this when grid size or scale changes
return getScale() * zone.getGrid().getSize();
}
/**
* This makes sure that any image updates get refreshed. This could be a little smarter.
*/
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
repaint();
return super.imageUpdate(img, infoflags, x, y, w, h);
}
private interface ItemRenderer {
public void render(Graphics2D g);
}
/**
* Represents a delayed label render
*/
private class LabelRenderer implements ItemRenderer {
private final String text;
private int x;
private final int y;
private final int align;
private final Color foreground;
private final ImageLabel background;
// Used for drawing from label cache.
private final GUID tokenId;
private int width, height;
public LabelRenderer(String text, int x, int y) {
this(text, x, y, null);
}
public LabelRenderer(String text, int x, int y, GUID tId) {
this.text = text;
this.x = x;
this.y = y;
// Defaults
this.align = SwingUtilities.CENTER;
this.background = GraphicsUtil.GREY_LABEL;
this.foreground = Color.black;
tokenId = tId;
if (tokenId != null) {
width = labelRenderingCache.get(tokenId).getWidth();
height = labelRenderingCache.get(tokenId).getHeight();
}
}
public LabelRenderer(String text, int x, int y, int align, ImageLabel background, Color foreground) {
this(text, x, y, align, background, foreground, null);
}
public LabelRenderer(String text, int x, int y, int align, ImageLabel background, Color foreground, GUID tId) {
this.text = text;
this.x = x;
this.y = y;
this.align = align;
this.foreground = foreground;
this.background = background;
tokenId = tId;
if (tokenId != null) {
width = labelRenderingCache.get(tokenId).getWidth();
height = labelRenderingCache.get(tokenId).getHeight();
}
}
public void render(Graphics2D g) {
if (tokenId != null) { // Use cached image.
switch (align) {
case SwingUtilities.CENTER:
x = x - width / 2;
break;
case SwingUtilities.RIGHT:
x = x - width;
break;
case SwingUtilities.LEFT:
break;
}
BufferedImage img = labelRenderingCache.get(tokenId);
if (img != null) {
g.drawImage(img, x, y, width, height, null);
} else { // Draw as normal
GraphicsUtil.drawBoxedString(g, text, x, y, align, background, foreground);
}
} else { // Draw as normal.
GraphicsUtil.drawBoxedString(g, text, x, y, align, background, foreground);
}
}
}
/**
* Represents a movement set
*/
private class SelectionSet {
private final HashSet<GUID> selectionSet = new HashSet<GUID>();
private final GUID keyToken;
private final String playerId;
private ZoneWalker walker;
private final Token token;
private Path<ZonePoint> gridlessPath;
// Pixel distance from keyToken's origin
private int offsetX;
private int offsetY;
public SelectionSet(String playerId, GUID tokenGUID, Set<GUID> selectionList) {
selectionSet.addAll(selectionList);
keyToken = tokenGUID;
this.playerId = playerId;
token = zone.getToken(tokenGUID);
if (token.isSnapToGrid() && zone.getGrid().getCapabilities().isSnapToGridSupported()) {
if (zone.getGrid().getCapabilities().isPathingSupported()) {
CellPoint tokenPoint = zone.getGrid().convert(new ZonePoint(token.getX(), token.getY()));
walker = zone.getGrid().createZoneWalker();
walker.setWaypoints(tokenPoint, tokenPoint);
}
} else {
gridlessPath = new Path<ZonePoint>();
gridlessPath.addPathCell(new ZonePoint(token.getX(), token.getY()));
}
}
public ZoneWalker getWalker() {
return walker;
}
public GUID getKeyToken() {
return keyToken;
}
public Set<GUID> getTokens() {
return selectionSet;
}
public boolean contains(Token token) {
return selectionSet.contains(token.getId());
}
public void setOffset(int x, int y) {
offsetX = x;
offsetY = y;
ZonePoint zp = new ZonePoint(token.getX() + x, token.getY() + y);
if (ZoneRenderer.this.zone.getGrid().getCapabilities().isPathingSupported() && token.isSnapToGrid()) {
CellPoint point = zone.getGrid().convert(zp);
walker.replaceLastWaypoint(point);
} else {
if (gridlessPath.getCellPath().size() > 1) {
gridlessPath.replaceLastPoint(zp);
} else {
gridlessPath.addPathCell(zp);
}
}
}
/**
* Add the waypoint if it is a new waypoint. If it is an old waypoint remove it.
*
* @param location
* The point where the waypoint is toggled.
*/
public void toggleWaypoint(ZonePoint location) {
// CellPoint cp = renderer.getZone().getGrid().convert(new ZonePoint(dragStartX, dragStartY));
if (walker != null && token.isSnapToGrid() && getZone().getGrid() != null) {
walker.toggleWaypoint(getZone().getGrid().convert(location));
} else {
gridlessPath.addWayPoint(location);
gridlessPath.addPathCell(location);
}
}
/**
* Retrieves the last waypoint, or if there isn't one then the start point of the first path segment.
*
* @param location
*/
public ZonePoint getLastWaypoint() {
ZonePoint zp;
if (walker != null && token.isSnapToGrid() && getZone().getGrid() != null) {
CellPoint cp = walker.getLastPoint();
zp = getZone().getGrid().convert(cp);
} else {
zp = gridlessPath.getLastJunctionPoint();
}
return zp;
}
public int getOffsetX() {
return offsetX;
}
public int getOffsetY() {
return offsetY;
}
public String getPlayerId() {
return playerId;
}
}
private class TokenLocation {
public Area bounds;
public Rectangle2D origBounds;
public Token token;
public Rectangle boundsCache;
public int height;
public int width;
public double scaledHeight;
public double scaledWidth;
public double x;
public double y;
public int offsetX;
public int offsetY;
public TokenLocation(Area bounds, Rectangle2D origBounds, Token token, double x, double y, int width, int height, double scaledWidth, double scaledHeight) {
this.bounds = bounds;
this.token = token;
this.origBounds = origBounds;
this.width = width;
this.height = height;
this.scaledWidth = scaledWidth;
this.scaledHeight = scaledHeight;
this.x = x;
this.y = y;
offsetX = getViewOffsetX();
offsetY = getViewOffsetY();
boundsCache = bounds.getBounds();
}
public boolean maybeOnscreen(Rectangle viewport) {
int deltaX = getViewOffsetX() - offsetX;
int deltaY = getViewOffsetY() - offsetY;
boundsCache.x += deltaX;
boundsCache.y += deltaY;
offsetX = getViewOffsetX();
offsetY = getViewOffsetY();
timer.start("maybeOnsceen");
if (!boundsCache.intersects(viewport)) {
timer.stop("maybeOnsceen");
return false;
}
timer.stop("maybeOnsceen");
return true;
}
}
private static class LabelLocation {
public Rectangle bounds;
public Label label;
public LabelLocation(Rectangle bounds, Label label) {
this.bounds = bounds;
this.label = label;
}
}
//
// DROP TARGET LISTENER
/*
* (non-Javadoc)
*
* @see java.awt.dnd.DropTargetListener#dragEnter(java.awt.dnd.DropTargetDragEvent )
*/
public void dragEnter(DropTargetDragEvent dtde) {
}
/*
* (non-Javadoc)
*
* @see java.awt.dnd.DropTargetListener#dragExit(java.awt.dnd.DropTargetEvent)
*/
public void dragExit(DropTargetEvent dte) {
}
/*
* (non-Javadoc)
*
* @see java.awt.dnd.DropTargetListener#dragOver (java.awt.dnd.DropTargetDragEvent)
*/
public void dragOver(DropTargetDragEvent dtde) {
}
private void addTokens(List<Token> tokens, ZonePoint zp, List<Boolean> configureTokens, boolean showDialog) {
GridCapabilities gridCaps = zone.getGrid().getCapabilities();
boolean isGM = MapTool.getPlayer().isGM();
List<String> failedPaste = new ArrayList<String>(tokens.size());
List<GUID> selectThese = new ArrayList<GUID>(tokens.size());
ScreenPoint sp = ScreenPoint.fromZonePoint(this, zp);
Point dropPoint = new Point((int) sp.x, (int) sp.y);
SwingUtilities.convertPointToScreen(dropPoint, this);
int tokenIndex = 0;
for (Token token : tokens) {
boolean configureToken = configureTokens.get(tokenIndex++);
// Get the snap to grid value for the current prefs and abilities
token.setSnapToGrid(gridCaps.isSnapToGridSupported() && AppPreferences.getTokensStartSnapToGrid());
if (token.isSnapToGrid()) {
zp = zone.getGrid().convert(zone.getGrid().convert(zp));
}
token.setX(zp.x);
token.setY(zp.y);
// Set the image properties
if (configureToken) {
BufferedImage image = ImageManager.getImageAndWait(token.getImageAssetId());
token.setShape(TokenUtil.guessTokenType(image));
token.setWidth(image.getWidth(null));
token.setHeight(image.getHeight(null));
token.setFootprint(zone.getGrid(), zone.getGrid().getDefaultFootprint());
}
// Always set the layer
token.setLayer(getActiveLayer());
// He who drops, owns, if there are not players already set
// and if there are already players set, add the current one to the list.
// (Cannot use AppUtil.playerOwns() since that checks 'isStrictTokenManagement' and we want real ownership here.
if (!isGM && (!token.hasOwners() || !token.isOwner(MapTool.getPlayer().getName()))) {
token.addOwner(MapTool.getPlayer().getName());
}
// Token type
Rectangle size = token.getBounds(zone);
switch (getActiveLayer()) {
case TOKEN:
// Players can't drop invisible tokens
token.setVisible(!isGM || AppPreferences.getNewTokensVisible());
if (AppPreferences.getTokensStartFreesize()) {
token.setSnapToScale(false);
}
break;
case BACKGROUND:
token.setShape(Token.TokenShape.TOP_DOWN);
token.setSnapToScale(!AppPreferences.getBackgroundsStartFreesize());
token.setSnapToGrid(AppPreferences.getBackgroundsStartSnapToGrid());
token.setVisible(AppPreferences.getNewBackgroundsVisible());
// Center on drop point
if (!token.isSnapToScale() && !token.isSnapToGrid()) {
token.setX(token.getX() - size.width / 2);
token.setY(token.getY() - size.height / 2);
}
break;
case OBJECT:
token.setShape(Token.TokenShape.TOP_DOWN);
token.setSnapToScale(!AppPreferences.getObjectsStartFreesize());
token.setSnapToGrid(AppPreferences.getObjectsStartSnapToGrid());
token.setVisible(AppPreferences.getNewObjectsVisible());
// Center on drop point
if (!token.isSnapToScale() && !token.isSnapToGrid()) {
token.setX(token.getX() - size.width / 2);
token.setY(token.getY() - size.height / 2);
}
break;
}
// FJE Yes, this looks redundant. But calling getType() retrieves the type of
// the Token and returns NPC if the type can't be determined (raw image,
// corrupted token file, etc). So retrieving it and then turning around and
// setting it ensures it has a valid value without necessarily changing what
// it was. :)
Token.Type type = token.getType();
token.setType(type);
// Token type
if (isGM) {
// Check the name (after Token layer is set as name relies on layer)
Token tokenNameUsed = zone.getTokenByName(token.getName());
if (tokenNameUsed != null)
token.setName(MapToolUtil.nextTokenId(zone, token));
if (getActiveLayer() == Zone.Layer.TOKEN) {
if (AppPreferences.getShowDialogOnNewToken() || showDialog) {
NewTokenDialog dialog = new NewTokenDialog(token, dropPoint.x, dropPoint.y);
dialog.showDialog();
if (!dialog.isSuccess()) {
continue;
}
}
}
} else {
// Player dropped, ensure it's a PC token
// (Why? Couldn't a Player drop an RPTOK that represents an NPC, such as for a summoned monster?
// Unfortunately, we can't know at this point whether the original input was an RPTOK or not.)
token.setType(Token.Type.PC);
// For Players, check to see if the name is already in use. If it is already in use, make sure the current Player
// owns the token being duplicated (to avoid subtle ways of manipulating someone else's token!).
Token tokenNameUsed = zone.getTokenByName(token.getName());
if (tokenNameUsed != null) {
if (!AppUtil.playerOwns(tokenNameUsed)) {
failedPaste.add(token.getName());
continue;
}
String newName = MapToolUtil.nextTokenId(zone, token);
token.setName(newName);
}
}
// Make sure all the assets are transfered
for (MD5Key id : token.getAllImageAssets()) {
Asset asset = AssetManager.getAsset(id);
if (asset == null) {
log.error("Could not find image for asset: " + id);
continue;
}
MapToolUtil.uploadAsset(asset);
}
// Save the token and tell everybody about it
zone.putToken(token);
MapTool.serverCommand().putToken(zone.getId(), token);
selectThese.add(token.getId());
}
// For convenience, select them
clearSelectedTokens();
selectTokens(selectThese);
if (!isGM)
MapTool.addMessage(TextMessage.gm(null, "Tokens dropped onto map '" + zone.getName() + "'"));
if (!failedPaste.isEmpty()) {
String mesg = "Failed to paste token(s) with duplicate name(s): " + failedPaste;
TextMessage msg = TextMessage.gm(null, mesg);
MapTool.addMessage(msg);
// msg.setChannel(Channel.ME);
// MapTool.addMessage(msg);
}
// Copy them to the clipboard so that we can quickly copy them onto the map
AppActions.copyTokens(tokens);
requestFocusInWindow();
repaint();
}
/*
* (non-Javadoc)
*
* @see java.awt.dnd.DropTargetListener#drop (java.awt.dnd.DropTargetDropEvent)
*/
public void drop(DropTargetDropEvent dtde) {
ZonePoint zp = new ScreenPoint((int) dtde.getLocation().getX(), (int) dtde.getLocation().getY()).convertToZone(this);
TransferableHelper th = (TransferableHelper) getTransferHandler();
List<Token> tokens = th.getTokens();
if (tokens != null && !tokens.isEmpty())
addTokens(tokens, zp, th.getConfigureTokens(), false);
}
public Set<GUID> getVisibleTokenSet() {
return visibleTokenSet;
}
/*
* (non-Javadoc)
*
* @see java.awt.dnd.DropTargetListener#dropActionChanged (java.awt.dnd.DropTargetDragEvent)
*/
public void dropActionChanged(DropTargetDragEvent dtde) {
}
//
// ZONE MODEL CHANGE LISTENER
private class ZoneModelChangeListener implements ModelChangeListener {
public void modelChanged(ModelChangeEvent event) {
Object evt = event.getEvent();
if (evt == Zone.Event.TOPOLOGY_CHANGED) {
flushFog();
flushLight();
}
if (evt == Zone.Event.TOKEN_CHANGED || evt == Zone.Event.TOKEN_REMOVED || evt == Zone.Event.TOKEN_ADDED) {
if (event.getArg() instanceof List<?>) {
@SuppressWarnings("unchecked")
List<Token> list = (List<Token>) (event.getArg());
for (Token token : list) {
flush(token);
}
} else {
flush((Token) event.getArg());
}
}
if (evt == Zone.Event.FOG_CHANGED) {
flushFog = true;
}
MapTool.getFrame().updateTokenTree();
repaint();
}
}
//
// COMPARABLE
public int compareTo(Object o) {
if (!(o instanceof ZoneRenderer)) {
return 0;
}
return zone.getCreationTime() < ((ZoneRenderer) o).zone.getCreationTime() ? -1 : 1;
}
// Begin token common macro identification
private List<Token> highlightCommonMacros = new ArrayList<Token>();
public List<Token> getHighlightCommonMacros() {
return highlightCommonMacros;
}
public void setHighlightCommonMacros(List<Token> affectedTokens) {
highlightCommonMacros = affectedTokens;
repaint();
}
// End token common macro identification
//
// IMAGE OBSERVER
private final ImageObserver drawableObserver = new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
ZoneRenderer.this.flushDrawableRenderer();
MapTool.getFrame().refresh();
return true;
}
};
/*
* (non-Javadoc)
*
* @see java.awt.Component#setCursor(java.awt.Cursor)
*/
@Override
public void setCursor(Cursor cursor) {
// System.out.println("Setting cursor on ZoneRenderer: " + cursor.toString());
if (false && cursor == Cursor.getDefaultCursor()) {
// if (custom == null)
custom = createCustomCursor("image/cursor.png", "Group");
cursor = custom;
}
super.setCursor(cursor);
}
private Cursor custom = null;
public Cursor createCustomCursor(String resource, String tokenName) {
Cursor c = null;
try {
// Dimension d = Toolkit.getDefaultToolkit().getBestCursorSize(16, 16); // On OSX returns any size up to 1/2 of (screen width, screen height)
// System.out.println("Best cursor size: " + d);
BufferedImage img = ImageIO.read(MapTool.class.getResourceAsStream(resource));
Font font = AppStyle.labelFont;
Graphics2D z = (Graphics2D) this.getGraphics();
z.setFont(font);
FontRenderContext frc = z.getFontRenderContext();
TextLayout tl = new TextLayout(tokenName, font, frc);
Rectangle textbox = tl.getPixelBounds(null, 0, 0);
// Now create a larger BufferedImage that will hold both the existing cursor and a token name
// Use the larger of the image width or string width, and the height of the image + the height of the string
// to represent the bounding box of the 'arrow+tokenName'
Rectangle bounds = new Rectangle(Math.max(img.getWidth(), textbox.width), img.getHeight() + textbox.height);
BufferedImage cursor = new BufferedImage(bounds.width, bounds.height, Transparency.TRANSLUCENT);
Graphics2D g2d = cursor.createGraphics();
g2d.setFont(font);
g2d.setComposite(z.getComposite());
g2d.setStroke(z.getStroke());
g2d.setPaintMode();
z.dispose();
Object oldAA = SwingUtil.useAntiAliasing(g2d);
// g2d.setTransform( ((Graphics2D)this.getGraphics()).getTransform() );
// g2d.drawImage(img, null, 0, 0);
g2d.drawImage(img, new AffineTransform(1f, 0f, 0f, 1f, 0, 0), null); // Draw the arrow at 1:1 resolution
g2d.translate(0, img.getHeight() + textbox.height / 2);
// g2d.transform(new AffineTransform(0.5f, 0f, 0f, 0.5f, 0, 0)); // Why do I need this to scale down the text??
g2d.setColor(Color.BLACK);
GraphicsUtil.drawBoxedString(g2d, tokenName, 0, 0, SwingUtilities.LEFT); // The text draw here is not nearly as nice looking as normal
// g2d.setBackground(Color.BLACK);
// g2d.setColor(Color.WHITE);
// g2d.fillRect(0, bounds.height-textbox.height, textbox.width, textbox.height);
// g2d.drawString(tokenName, 0F, bounds.height - descent);
g2d.dispose();
c = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), tokenName);
SwingUtil.restoreAntiAliasing(g2d, oldAA);
img.flush(); // Try to be friendly about memory usage. ;-)
cursor.flush();
} catch (Exception e) {
}
return c;
}
}
| true | true | protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) {
Graphics2D clippedG = g;
boolean isGMView = view.isGMView(); // speed things up
timer.start("createClip");
if (!isGMView && visibleScreenArea != null && !tokenList.isEmpty() && tokenList.get(0).isToken()) {
clippedG = (Graphics2D) g.create();
Area visibleArea = new Area(g.getClipBounds());
visibleArea.intersect(visibleScreenArea);
clippedG.setClip(new GeneralPath(visibleArea));
}
timer.stop("createClip");
// This is in screen coordinates
Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height);
Rectangle clipBounds = g.getClipBounds();
double scale = zoneScale.getScale();
Set<GUID> tempVisTokens = new HashSet<GUID>();
// calculations
boolean calculateStacks = !tokenList.isEmpty() && !tokenList.get(0).isStamp() && tokenStackMap == null;
if (calculateStacks) {
tokenStackMap = new HashMap<Token, Set<Token>>();
}
List<Token> tokenPostProcessing = new ArrayList<Token>(tokenList.size());
for (Token token : tokenList) {
timer.start("tokenlist-1");
try {
if (token.isStamp() && isTokenMoving(token)) {
continue;
}
// Don't bother if it's not visible
// NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster
// to just draw the tokens and let them be clipped
if (!token.isVisible() && !isGMView) {
continue;
}
if (token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(token)) {
continue;
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1");
}
timer.start("tokenlist-1.1");
TokenLocation location = tokenLocationCache.get(token);
if (location != null && !location.maybeOnscreen(viewport)) {
timer.stop("tokenlist-1.1");
continue;
}
timer.stop("tokenlist-1.1");
timer.start("tokenlist-1a");
Rectangle footprintBounds = token.getBounds(zone);
timer.stop("tokenlist-1a");
timer.start("tokenlist-1b");
BufferedImage image = ImageManager.getImage(token.getImageAssetId(), this);
timer.stop("tokenlist-1b");
timer.start("tokenlist-1c");
double scaledWidth = (footprintBounds.width * scale);
double scaledHeight = (footprintBounds.height * scale);
// if (!token.isStamp()) {
// // Fit inside the grid
// scaledWidth --;
// scaledHeight --;
// }
ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
timer.stop("tokenlist-1c");
timer.start("tokenlist-1d");
// Tokens are centered on the image center point
double x = tokenScreenLocation.x;
double y = tokenScreenLocation.y;
Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight);
Area tokenBounds = new Area(origBounds);
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
double sx = scaledWidth / 2 + x - (token.getAnchor().x * scale);
double sy = scaledHeight / 2 + y - (token.getAnchor().x * scale);
tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), sx, sy)); // facing defaults to down, or -90 degrees
}
timer.stop("tokenlist-1d");
timer.start("tokenlist-1e");
try {
location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight);
tokenLocationCache.put(token, location);
// Too small ?
if (location.scaledHeight < 1 || location.scaledWidth < 1) {
continue;
}
// Vision visibility
if (!isGMView && token.isToken() && zoneView.isUsingVision()) {
if (!GraphicsUtil.intersects(visibleScreenArea, location.bounds)) {
continue;
}
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1e");
}
// Markers
timer.start("renderTokens:Markers");
if (token.isMarker() && canSeeMarker(token)) {
markerLocationList.add(location);
}
timer.stop("renderTokens:Markers");
// Stacking check
if (calculateStacks) {
timer.start("tokenStack");
// System.out.println(token.getName() + " - " + location.boundsCache);
Set<Token> tokenStackSet = null;
for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) {
// Are we covering anyone ?
// System.out.println("\t" + currLocation.token.getName() + " - " + location.boundsCache.contains(currLocation.boundsCache));
if (location.boundsCache.contains(currLocation.boundsCache)) {
if (tokenStackSet == null) {
tokenStackSet = new HashSet<Token>();
tokenStackMap.put(token, tokenStackSet);
tokenStackSet.add(token);
}
tokenStackSet.add(currLocation.token);
if (tokenStackMap.get(currLocation.token) != null) {
tokenStackSet.addAll(tokenStackMap.get(currLocation.token));
tokenStackMap.remove(currLocation.token);
}
}
}
timer.stop("tokenStack");
}
// Keep track of the location on the screen
// Note the order -- the top most token is at the end of the list
timer.start("renderTokens:Locations");
Zone.Layer layer = token.getLayer();
List<TokenLocation> locationList = getTokenLocations(layer);
if (locationList != null) {
locationList.add(location);
}
timer.stop("renderTokens:Locations");
// Add the token to our visible set.
tempVisTokens.add(token.getId());
// Only draw if we're visible
// NOTE: this takes place AFTER resizing the image, that's so that the user
// suffers a pause only once while scaling, and not as new tokens are
// scrolled onto the screen
timer.start("renderTokens:OnscreenCheck");
if (!location.bounds.intersects(clipBounds)) {
timer.stop("renderTokens:OnscreenCheck");
continue;
}
timer.stop("renderTokens:OnscreenCheck");
// Moving ?
timer.start("renderTokens:ShowMovement");
if (isTokenMoving(token)) {
BufferedImage replacementImage = replacementImageMap.get(token);
if (replacementImage == null) {
replacementImage = ImageUtil.rgbToGrayscale(image);
replacementImageMap.put(token, replacementImage);
}
image = replacementImage;
}
timer.stop("renderTokens:ShowMovement");
// Previous path
timer.start("renderTokens:ShowPath");
if (showPathList.contains(token) && token.getLastPath() != null) {
renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid()));
}
timer.stop("renderTokens:ShowPath");
timer.start("tokenlist-4");
// Halo (TOPDOWN, CIRCLE)
if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) {
Stroke oldStroke = clippedG.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight));
clippedG.setStroke(oldStroke);
}
timer.stop("tokenlist-4");
timer.start("tokenlist-5");
// handle flipping
BufferedImage workImage = image;
if (token.isFlippedX() || token.isFlippedY()) {
workImage = flipImageMap.get(token);
if (workImage == null) {
workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency());
int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1);
int workH = image.getHeight() * (token.isFlippedY() ? -1 : 1);
int workX = token.isFlippedX() ? image.getWidth() : 0;
int workY = token.isFlippedY() ? image.getHeight() : 0;
Graphics2D wig = workImage.createGraphics();
wig.drawImage(image, workX, workY, workW, workH, null);
wig.dispose();
flipImageMap.put(token, workImage);
}
}
timer.stop("tokenlist-5");
timer.start("tokenlist-6");
// Position
Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight());
SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height);
int offsetx = 0;
int offsety = 0;
if (token.isSnapToScale()) {
offsetx = (int) (imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width) / 2 * getScale() : 0);
offsety = (int) (imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height) / 2 * getScale() : 0);
}
double tx = location.x + offsetx;
double ty = location.y + offsety;
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
// Rotated
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth / 2 - (token.getAnchor().x * scale) - offsetx, location.scaledHeight / 2 - (token.getAnchor().y * scale)
- offsety);
// facing defaults to down, or -90 degrees
}
// Draw the token
if (token.isSnapToScale()) {
at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight());
at.scale(getScale(), getScale());
} else {
at.scale((scaledWidth) / workImage.getWidth(), (scaledHeight) / workImage.getHeight());
}
timer.stop("tokenlist-6");
timer.start("tokenlist-7");
clippedG.drawImage(workImage, at, this);
timer.stop("tokenlist-7");
timer.start("tokenlist-8");
// Halo (SQUARE)
// XXX Why are square halos drawn separately?!
if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) {
Stroke oldStroke = g.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight));
clippedG.setStroke(oldStroke);
}
// Facing ?
// TODO: Optimize this by doing it once per token per facing
if (token.hasFacing()) {
Token.TokenShape tokenType = token.getShape();
switch (tokenType) {
case CIRCLE:
Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width / 2);
double cx = location.x + location.scaledWidth / 2;
double cy = location.y + location.scaledHeight / 2;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
case SQUARE:
int facing = token.getFacing();
while (facing < 0) {
facing += 360;
} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff
facing %= 360;
arrow = getSquareFacingArrow(facing, footprintBounds.width / 2);
cx = location.x + location.scaledWidth / 2;
cy = location.y + location.scaledHeight / 2;
// Find the edge of the image
// TODO: Man, this is horrible, there's gotta be a better way to do this
double xp = location.scaledWidth / 2;
double yp = location.scaledHeight / 2;
if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) {
xp = (int) (yp / Math.tan(Math.toRadians(facing)));
if (facing > 180) {
xp = -xp;
yp = -yp;
}
} else {
yp = (int) (xp * Math.tan(Math.toRadians(facing)));
if (facing > 90 && facing < 270) {
xp = -xp;
yp = -yp;
}
}
cx += xp;
cy -= yp;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
}
}
timer.stop("tokenlist-8");
timer.start("tokenlist-9");
// Set up the graphics so that the overlay can just be painted.
Graphics2D locg = (Graphics2D) clippedG.create((int) location.x, (int) location.y, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
Rectangle bounds = new Rectangle(0, 0, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
// Check each of the set values
for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) {
Object stateValue = token.getState(state);
AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state);
if (stateValue instanceof AbstractTokenOverlay) {
overlay = (AbstractTokenOverlay) stateValue;
}
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, stateValue);
}
timer.stop("tokenlist-9");
timer.start("tokenlist-10");
for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) {
Object barValue = token.getState(bar);
BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar);
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, barValue);
} // endfor
locg.dispose();
timer.stop("tokenlist-10");
timer.start("tokenlist-11");
// Keep track of which tokens have been drawn so we can perform post-processing on them later
// (such as selection borders and names/labels)
if (getActiveLayer().equals(token.getLayer()))
tokenPostProcessing.add(token);
timer.stop("tokenlist-11");
// DEBUGGING
// ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY()));
// g.setColor(Color.red);
// g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height);
// g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y);
}
timer.start("tokenlist-12");
boolean useIF = MapTool.getServerPolicy().isUseIndividualFOW();
// Selection and labels
for (Token token : tokenPostProcessing) {
TokenLocation location = tokenLocationCache.get(token);
if (location == null)
continue;
Area bounds = location.bounds;
// TODO: This isn't entirely accurate as it doesn't account for the actual text
// to be in the clipping bounds, but I'll fix that later
if (!bounds.getBounds().intersects(clipBounds)) {
continue;
}
Rectangle footprintBounds = token.getBounds(zone);
boolean isSelected = selectedTokenSet.contains(token.getId());
if (isSelected) {
ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
double width = footprintBounds.width * getScale();
double height = footprintBounds.height * getScale();
ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder;
if (highlightCommonMacros.contains(token)) {
selectedBorder = AppStyle.commonMacroBorder;
}
if (!AppUtil.playerOwns(token)) {
selectedBorder = AppStyle.selectedUnownedBorder;
}
if (useIF && !token.isStamp() && zoneView.isUsingVision()) {
Tool tool = MapTool.getFrame().getToolbox().getSelectedTool();
if (tool instanceof RectangleExposeTool // XXX Change to use marker interface such as ExposeTool?
|| tool instanceof OvalExposeTool || tool instanceof FreehandExposeTool || tool instanceof PolygonExposeTool)
selectedBorder = AppConstants.FOW_TOOLS_BORDER;
}
if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp())) {
AffineTransform oldTransform = clippedG.getTransform();
// Rotated
clippedG.translate(sp.x, sp.y);
clippedG.rotate(Math.toRadians(-token.getFacing() - 90), width / 2 - (token.getAnchor().x * scale), height / 2 - (token.getAnchor().y * scale)); // facing defaults to down, or -90 degrees
selectedBorder.paintAround(clippedG, 0, 0, (int) width, (int) height);
clippedG.setTransform(oldTransform);
} else {
selectedBorder.paintAround(clippedG, (int) sp.x, (int) sp.y, (int) width, (int) height);
}
// Remove labels from the cache if the corresponding tokens are deselected
} else if (!AppState.isShowTokenNames() && labelRenderingCache.containsKey(token.getId())) {
labelRenderingCache.remove(token.getId());
}
// Token names and labels
boolean showCurrentTokenLabel = AppState.isShowTokenNames() || token == tokenUnderMouse;
if (showCurrentTokenLabel) {
GUID tokId = token.getId();
int offset = 3; // Keep it from tramping on the token border.
ImageLabel background;
Color foreground;
if (token.isVisible()) {
if (token.getType() == Token.Type.NPC) {
background = GraphicsUtil.BLUE_LABEL;
foreground = Color.WHITE;
} else {
background = GraphicsUtil.GREY_LABEL;
foreground = Color.BLACK;
}
} else {
background = GraphicsUtil.DARK_GREY_LABEL;
foreground = Color.WHITE;
}
String name = token.getName();
if (isGMView && token.getGMName() != null && !StringUtil.isEmpty(token.getGMName())) {
name += " (" + token.getGMName() + ")";
}
if (!view.equals(lastView) || !labelRenderingCache.containsKey(tokId)) {
// if ((lastView != null && !lastView.equals(view)) || !labelRenderingCache.containsKey(tokId)) {
boolean hasLabel = false;
// Calculate image dimensions
FontMetrics fm = g.getFontMetrics();
Font f = g.getFont();
int strWidth = SwingUtilities.computeStringWidth(fm, name);
int width = strWidth + GraphicsUtil.BOX_PADDINGX * 2;
int height = fm.getHeight() + GraphicsUtil.BOX_PADDINGY * 2;
int labelHeight = height;
// If token has a label (in addition to name).
if (token.getLabel() != null && token.getLabel().trim().length() > 0) {
hasLabel = true;
height = height * 2; // Double the image height for two boxed strings.
int labelWidth = SwingUtilities.computeStringWidth(fm, token.getLabel()) + GraphicsUtil.BOX_PADDINGX * 2;
width = (width > labelWidth) ? width : labelWidth;
}
// Set up the image
BufferedImage labelRender = new BufferedImage(width, height, Transparency.TRANSLUCENT);
Graphics2D gLabelRender = labelRender.createGraphics();
gLabelRender.setFont(f); // Match font used in the main graphics context.
gLabelRender.setRenderingHints(g.getRenderingHints()); // Match rendering style.
// Draw name and label to image
if (hasLabel) {
GraphicsUtil.drawBoxedString(gLabelRender, token.getLabel(), width / 2, height - (labelHeight / 2), SwingUtilities.CENTER, background, foreground);
}
GraphicsUtil.drawBoxedString(gLabelRender, name, width / 2, labelHeight / 2, SwingUtilities.CENTER, background, foreground);
// Add image to cache
labelRenderingCache.put(tokId, labelRender);
}
// Create LabelRenderer using cached label.
Rectangle r = bounds.getBounds();
delayRendering(new LabelRenderer(name, r.x + r.width / 2, r.y + r.height + offset, SwingUtilities.CENTER, background, foreground, tokId));
}
}
timer.stop("tokenlist-12");
timer.start("tokenlist-13");
// Stacks
if (!tokenList.isEmpty() && !tokenList.get(0).isStamp()) { // TODO: find a cleaner way to indicate token layer
if (tokenStackMap != null) { // FIXME Needed to prevent NPE but how can it be null?
for (Token token : tokenStackMap.keySet()) {
Area bounds = getTokenBounds(token);
if (bounds == null) {
// token is offscreen
continue;
}
BufferedImage stackImage = AppStyle.stackImage;
clippedG.drawImage(stackImage, bounds.getBounds().x + bounds.getBounds().width - stackImage.getWidth() + 2, bounds.getBounds().y - 2, null);
}
}
}
// Markers
// for (TokenLocation location : getMarkerLocations()) {
// BufferedImage stackImage = AppStyle.markerImage;
// g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null);
// }
if (clippedG != g) {
clippedG.dispose();
}
timer.stop("tokenlist-13");
visibleTokenSet = Collections.unmodifiableSet(tempVisTokens);
}
| protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) {
Graphics2D clippedG = g;
boolean isGMView = view.isGMView(); // speed things up
timer.start("createClip");
if (!isGMView && visibleScreenArea != null && !tokenList.isEmpty() && tokenList.get(0).isToken()) {
clippedG = (Graphics2D) g.create();
Area visibleArea = new Area(g.getClipBounds());
visibleArea.intersect(visibleScreenArea);
clippedG.setClip(new GeneralPath(visibleArea));
}
timer.stop("createClip");
// This is in screen coordinates
Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height);
Rectangle clipBounds = g.getClipBounds();
double scale = zoneScale.getScale();
Set<GUID> tempVisTokens = new HashSet<GUID>();
// calculations
boolean calculateStacks = !tokenList.isEmpty() && !tokenList.get(0).isStamp() && tokenStackMap == null;
if (calculateStacks) {
tokenStackMap = new HashMap<Token, Set<Token>>();
}
List<Token> tokenPostProcessing = new ArrayList<Token>(tokenList.size());
for (Token token : tokenList) {
timer.start("tokenlist-1");
try {
if (token.isStamp() && isTokenMoving(token)) {
continue;
}
// Don't bother if it's not visible
// NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster
// to just draw the tokens and let them be clipped
if (!token.isVisible() && !isGMView) {
continue;
}
if (token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(token)) {
continue;
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1");
}
timer.start("tokenlist-1.1");
TokenLocation location = tokenLocationCache.get(token);
if (location != null && !location.maybeOnscreen(viewport)) {
timer.stop("tokenlist-1.1");
continue;
}
timer.stop("tokenlist-1.1");
timer.start("tokenlist-1a");
Rectangle footprintBounds = token.getBounds(zone);
timer.stop("tokenlist-1a");
timer.start("tokenlist-1b");
BufferedImage image = ImageManager.getImage(token.getImageAssetId(), this);
timer.stop("tokenlist-1b");
timer.start("tokenlist-1c");
double scaledWidth = (footprintBounds.width * scale);
double scaledHeight = (footprintBounds.height * scale);
// if (!token.isStamp()) {
// // Fit inside the grid
// scaledWidth --;
// scaledHeight --;
// }
ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
timer.stop("tokenlist-1c");
timer.start("tokenlist-1d");
// Tokens are centered on the image center point
double x = tokenScreenLocation.x;
double y = tokenScreenLocation.y;
Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight);
Area tokenBounds = new Area(origBounds);
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
double sx = scaledWidth / 2 + x - (token.getAnchor().x * scale);
double sy = scaledHeight / 2 + y - (token.getAnchor().x * scale);
tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), sx, sy)); // facing defaults to down, or -90 degrees
}
timer.stop("tokenlist-1d");
timer.start("tokenlist-1e");
try {
location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight);
tokenLocationCache.put(token, location);
// Too small ?
if (location.scaledHeight < 1 || location.scaledWidth < 1) {
continue;
}
// Vision visibility
if (!isGMView && token.isToken() && zoneView.isUsingVision()) {
if (!GraphicsUtil.intersects(visibleScreenArea, location.bounds)) {
continue;
}
}
} finally {
// This ensures that the timer is always stopped
timer.stop("tokenlist-1e");
}
// Markers
timer.start("renderTokens:Markers");
if (token.isMarker() && canSeeMarker(token)) {
markerLocationList.add(location);
}
timer.stop("renderTokens:Markers");
// Stacking check
if (calculateStacks) {
timer.start("tokenStack");
// System.out.println(token.getName() + " - " + location.boundsCache);
Set<Token> tokenStackSet = null;
for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) {
// Are we covering anyone ?
// System.out.println("\t" + currLocation.token.getName() + " - " + location.boundsCache.contains(currLocation.boundsCache));
if (location.boundsCache.contains(currLocation.boundsCache)) {
if (tokenStackSet == null) {
tokenStackSet = new HashSet<Token>();
tokenStackMap.put(token, tokenStackSet);
tokenStackSet.add(token);
}
tokenStackSet.add(currLocation.token);
if (tokenStackMap.get(currLocation.token) != null) {
tokenStackSet.addAll(tokenStackMap.get(currLocation.token));
tokenStackMap.remove(currLocation.token);
}
}
}
timer.stop("tokenStack");
}
// Keep track of the location on the screen
// Note the order -- the top most token is at the end of the list
timer.start("renderTokens:Locations");
Zone.Layer layer = token.getLayer();
List<TokenLocation> locationList = getTokenLocations(layer);
if (locationList != null) {
locationList.add(location);
}
timer.stop("renderTokens:Locations");
// Add the token to our visible set.
tempVisTokens.add(token.getId());
// Only draw if we're visible
// NOTE: this takes place AFTER resizing the image, that's so that the user
// suffers a pause only once while scaling, and not as new tokens are
// scrolled onto the screen
timer.start("renderTokens:OnscreenCheck");
if (!location.bounds.intersects(clipBounds)) {
timer.stop("renderTokens:OnscreenCheck");
continue;
}
timer.stop("renderTokens:OnscreenCheck");
// Moving ?
timer.start("renderTokens:ShowMovement");
if (isTokenMoving(token)) {
BufferedImage replacementImage = replacementImageMap.get(token);
if (replacementImage == null) {
replacementImage = ImageUtil.rgbToGrayscale(image);
replacementImageMap.put(token, replacementImage);
}
image = replacementImage;
}
timer.stop("renderTokens:ShowMovement");
// Previous path
timer.start("renderTokens:ShowPath");
if (showPathList.contains(token) && token.getLastPath() != null) {
renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid()));
}
timer.stop("renderTokens:ShowPath");
timer.start("tokenlist-4");
// Halo (TOPDOWN, CIRCLE)
if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) {
Stroke oldStroke = clippedG.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
clippedG.draw(location.bounds);
clippedG.setStroke(oldStroke);
}
timer.stop("tokenlist-4");
timer.start("tokenlist-5");
// handle flipping
BufferedImage workImage = image;
if (token.isFlippedX() || token.isFlippedY()) {
workImage = flipImageMap.get(token);
if (workImage == null) {
workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency());
int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1);
int workH = image.getHeight() * (token.isFlippedY() ? -1 : 1);
int workX = token.isFlippedX() ? image.getWidth() : 0;
int workY = token.isFlippedY() ? image.getHeight() : 0;
Graphics2D wig = workImage.createGraphics();
wig.drawImage(image, workX, workY, workW, workH, null);
wig.dispose();
flipImageMap.put(token, workImage);
}
}
timer.stop("tokenlist-5");
timer.start("tokenlist-6");
// Position
Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight());
SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height);
int offsetx = 0;
int offsety = 0;
if (token.isSnapToScale()) {
offsetx = (int) (imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width) / 2 * getScale() : 0);
offsety = (int) (imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height) / 2 * getScale() : 0);
}
double tx = location.x + offsetx;
double ty = location.y + offsety;
AffineTransform at = new AffineTransform();
at.translate(tx, ty);
// Rotated
if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) {
at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth / 2 - (token.getAnchor().x * scale) - offsetx, location.scaledHeight / 2 - (token.getAnchor().y * scale)
- offsety);
// facing defaults to down, or -90 degrees
}
// Draw the token
if (token.isSnapToScale()) {
at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight());
at.scale(getScale(), getScale());
} else {
at.scale((scaledWidth) / workImage.getWidth(), (scaledHeight) / workImage.getHeight());
}
timer.stop("tokenlist-6");
timer.start("tokenlist-7");
clippedG.drawImage(workImage, at, this);
timer.stop("tokenlist-7");
timer.start("tokenlist-8");
// Halo (SQUARE)
// XXX Why are square halos drawn separately?!
if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) {
Stroke oldStroke = g.getStroke();
clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth()));
clippedG.setColor(token.getHaloColor());
clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight));
clippedG.setStroke(oldStroke);
}
// Facing ?
// TODO: Optimize this by doing it once per token per facing
if (token.hasFacing()) {
Token.TokenShape tokenType = token.getShape();
switch (tokenType) {
case CIRCLE:
Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width / 2);
double cx = location.x + location.scaledWidth / 2;
double cy = location.y + location.scaledHeight / 2;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
case SQUARE:
int facing = token.getFacing();
while (facing < 0) {
facing += 360;
} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff
facing %= 360;
arrow = getSquareFacingArrow(facing, footprintBounds.width / 2);
cx = location.x + location.scaledWidth / 2;
cy = location.y + location.scaledHeight / 2;
// Find the edge of the image
// TODO: Man, this is horrible, there's gotta be a better way to do this
double xp = location.scaledWidth / 2;
double yp = location.scaledHeight / 2;
if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) {
xp = (int) (yp / Math.tan(Math.toRadians(facing)));
if (facing > 180) {
xp = -xp;
yp = -yp;
}
} else {
yp = (int) (xp * Math.tan(Math.toRadians(facing)));
if (facing > 90 && facing < 270) {
xp = -xp;
yp = -yp;
}
}
cx += xp;
cy -= yp;
clippedG.translate(cx, cy);
clippedG.setColor(Color.yellow);
clippedG.fill(arrow);
clippedG.setColor(Color.darkGray);
clippedG.draw(arrow);
clippedG.translate(-cx, -cy);
break;
}
}
timer.stop("tokenlist-8");
timer.start("tokenlist-9");
// Set up the graphics so that the overlay can just be painted.
Graphics2D locg = (Graphics2D) clippedG.create((int) location.x, (int) location.y, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
Rectangle bounds = new Rectangle(0, 0, (int) Math.ceil(location.scaledWidth), (int) Math.ceil(location.scaledHeight));
// Check each of the set values
for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) {
Object stateValue = token.getState(state);
AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state);
if (stateValue instanceof AbstractTokenOverlay) {
overlay = (AbstractTokenOverlay) stateValue;
}
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, stateValue);
}
timer.stop("tokenlist-9");
timer.start("tokenlist-10");
for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) {
Object barValue = token.getState(bar);
BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar);
if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) {
continue;
}
overlay.paintOverlay(locg, token, bounds, barValue);
} // endfor
locg.dispose();
timer.stop("tokenlist-10");
timer.start("tokenlist-11");
// Keep track of which tokens have been drawn so we can perform post-processing on them later
// (such as selection borders and names/labels)
if (getActiveLayer().equals(token.getLayer()))
tokenPostProcessing.add(token);
timer.stop("tokenlist-11");
// DEBUGGING
// ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY()));
// g.setColor(Color.red);
// g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height);
// g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y);
}
timer.start("tokenlist-12");
boolean useIF = MapTool.getServerPolicy().isUseIndividualFOW();
// Selection and labels
for (Token token : tokenPostProcessing) {
TokenLocation location = tokenLocationCache.get(token);
if (location == null)
continue;
Area bounds = location.bounds;
// TODO: This isn't entirely accurate as it doesn't account for the actual text
// to be in the clipping bounds, but I'll fix that later
if (!bounds.getBounds().intersects(clipBounds)) {
continue;
}
Rectangle footprintBounds = token.getBounds(zone);
boolean isSelected = selectedTokenSet.contains(token.getId());
if (isSelected) {
ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y);
double width = footprintBounds.width * getScale();
double height = footprintBounds.height * getScale();
ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder;
if (highlightCommonMacros.contains(token)) {
selectedBorder = AppStyle.commonMacroBorder;
}
if (!AppUtil.playerOwns(token)) {
selectedBorder = AppStyle.selectedUnownedBorder;
}
if (useIF && !token.isStamp() && zoneView.isUsingVision()) {
Tool tool = MapTool.getFrame().getToolbox().getSelectedTool();
if (tool instanceof RectangleExposeTool // XXX Change to use marker interface such as ExposeTool?
|| tool instanceof OvalExposeTool || tool instanceof FreehandExposeTool || tool instanceof PolygonExposeTool)
selectedBorder = AppConstants.FOW_TOOLS_BORDER;
}
if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp())) {
AffineTransform oldTransform = clippedG.getTransform();
// Rotated
clippedG.translate(sp.x, sp.y);
clippedG.rotate(Math.toRadians(-token.getFacing() - 90), width / 2 - (token.getAnchor().x * scale), height / 2 - (token.getAnchor().y * scale)); // facing defaults to down, or -90 degrees
selectedBorder.paintAround(clippedG, 0, 0, (int) width, (int) height);
clippedG.setTransform(oldTransform);
} else {
selectedBorder.paintAround(clippedG, (int) sp.x, (int) sp.y, (int) width, (int) height);
}
// Remove labels from the cache if the corresponding tokens are deselected
} else if (!AppState.isShowTokenNames() && labelRenderingCache.containsKey(token.getId())) {
labelRenderingCache.remove(token.getId());
}
// Token names and labels
boolean showCurrentTokenLabel = AppState.isShowTokenNames() || token == tokenUnderMouse;
if (showCurrentTokenLabel) {
GUID tokId = token.getId();
int offset = 3; // Keep it from tramping on the token border.
ImageLabel background;
Color foreground;
if (token.isVisible()) {
if (token.getType() == Token.Type.NPC) {
background = GraphicsUtil.BLUE_LABEL;
foreground = Color.WHITE;
} else {
background = GraphicsUtil.GREY_LABEL;
foreground = Color.BLACK;
}
} else {
background = GraphicsUtil.DARK_GREY_LABEL;
foreground = Color.WHITE;
}
String name = token.getName();
if (isGMView && token.getGMName() != null && !StringUtil.isEmpty(token.getGMName())) {
name += " (" + token.getGMName() + ")";
}
if (!view.equals(lastView) || !labelRenderingCache.containsKey(tokId)) {
// if ((lastView != null && !lastView.equals(view)) || !labelRenderingCache.containsKey(tokId)) {
boolean hasLabel = false;
// Calculate image dimensions
FontMetrics fm = g.getFontMetrics();
Font f = g.getFont();
int strWidth = SwingUtilities.computeStringWidth(fm, name);
int width = strWidth + GraphicsUtil.BOX_PADDINGX * 2;
int height = fm.getHeight() + GraphicsUtil.BOX_PADDINGY * 2;
int labelHeight = height;
// If token has a label (in addition to name).
if (token.getLabel() != null && token.getLabel().trim().length() > 0) {
hasLabel = true;
height = height * 2; // Double the image height for two boxed strings.
int labelWidth = SwingUtilities.computeStringWidth(fm, token.getLabel()) + GraphicsUtil.BOX_PADDINGX * 2;
width = (width > labelWidth) ? width : labelWidth;
}
// Set up the image
BufferedImage labelRender = new BufferedImage(width, height, Transparency.TRANSLUCENT);
Graphics2D gLabelRender = labelRender.createGraphics();
gLabelRender.setFont(f); // Match font used in the main graphics context.
gLabelRender.setRenderingHints(g.getRenderingHints()); // Match rendering style.
// Draw name and label to image
if (hasLabel) {
GraphicsUtil.drawBoxedString(gLabelRender, token.getLabel(), width / 2, height - (labelHeight / 2), SwingUtilities.CENTER, background, foreground);
}
GraphicsUtil.drawBoxedString(gLabelRender, name, width / 2, labelHeight / 2, SwingUtilities.CENTER, background, foreground);
// Add image to cache
labelRenderingCache.put(tokId, labelRender);
}
// Create LabelRenderer using cached label.
Rectangle r = bounds.getBounds();
delayRendering(new LabelRenderer(name, r.x + r.width / 2, r.y + r.height + offset, SwingUtilities.CENTER, background, foreground, tokId));
}
}
timer.stop("tokenlist-12");
timer.start("tokenlist-13");
// Stacks
if (!tokenList.isEmpty() && !tokenList.get(0).isStamp()) { // TODO: find a cleaner way to indicate token layer
if (tokenStackMap != null) { // FIXME Needed to prevent NPE but how can it be null?
for (Token token : tokenStackMap.keySet()) {
Area bounds = getTokenBounds(token);
if (bounds == null) {
// token is offscreen
continue;
}
BufferedImage stackImage = AppStyle.stackImage;
clippedG.drawImage(stackImage, bounds.getBounds().x + bounds.getBounds().width - stackImage.getWidth() + 2, bounds.getBounds().y - 2, null);
}
}
}
// Markers
// for (TokenLocation location : getMarkerLocations()) {
// BufferedImage stackImage = AppStyle.markerImage;
// g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null);
// }
if (clippedG != g) {
clippedG.dispose();
}
timer.stop("tokenlist-13");
visibleTokenSet = Collections.unmodifiableSet(tempVisTokens);
}
|
diff --git a/edu/wisc/ssec/mcidasv/chooser/McIdasBridgeChooser.java b/edu/wisc/ssec/mcidasv/chooser/McIdasBridgeChooser.java
index 73265a196..e0c93793b 100644
--- a/edu/wisc/ssec/mcidasv/chooser/McIdasBridgeChooser.java
+++ b/edu/wisc/ssec/mcidasv/chooser/McIdasBridgeChooser.java
@@ -1,279 +1,279 @@
/*
* $Id$
*
* Copyright 2007-2008
* Space Science and Engineering Center (SSEC)
* University of Wisconsin - Madison,
* 1225 W. Dayton Street, Madison, WI 53706, USA
*
* http://www.ssec.wisc.edu/mcidas
*
* This file is part of McIDAS-V.
*
* McIDAS-V is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* McIDAS-V 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see http://www.gnu.org/licenses
*/
package edu.wisc.ssec.mcidasv.chooser;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.w3c.dom.Element;
import ucar.unidata.idv.chooser.IdvChooser;
import ucar.unidata.idv.chooser.IdvChooserManager;
import ucar.unidata.util.GuiUtils;
import ucar.unidata.util.LogUtil;
import edu.wisc.ssec.mcidasv.Constants;
import edu.wisc.ssec.mcidasv.data.McIdasFrame;
import edu.wisc.ssec.mcidasv.data.McIdasXInfo;
import edu.wisc.ssec.mcidasv.util.McVGuiUtils;
import edu.wisc.ssec.mcidasv.util.McVGuiUtils.Position;
import edu.wisc.ssec.mcidasv.util.McVGuiUtils.TextColor;
import edu.wisc.ssec.mcidasv.util.McVGuiUtils.Width;
public class McIdasBridgeChooser extends IdvChooser implements Constants {
/** A widget for the command line text */
private JTextField hostLine = new JTextField("");
private JTextField portLine = new JTextField("");
private JTextField keyLine = new JTextField("");
private McIdasXInfo mcidasxInfo;
/**
* Create the chooser with the given manager and xml
*
* @param mgr The manager
* @param root The xml
*
*/
public McIdasBridgeChooser(IdvChooserManager mgr, Element root) {
super(mgr, root);
mcidasxInfo = new McIdasXInfo();
loadButton = McVGuiUtils.makeImageTextButton(ICON_ACCEPT_SMALL, getLoadCommandName());
loadButton.setActionCommand(getLoadCommandName());
loadButton.addActionListener(this);
}
public String getHost() {
return this.mcidasxInfo.getHostString();
}
private void setHost() {
this.mcidasxInfo.setHostString((hostLine.getText()).trim());
}
public String getPort() {
return this.mcidasxInfo.getPortString();
}
private void setPort() {
this.mcidasxInfo.setPortString((portLine.getText()).trim());
}
public String getKey() {
return this.mcidasxInfo.getPortString();
}
private void setKey() {
this.mcidasxInfo.setKeyString((keyLine.getText()).trim());
}
/**
* Returns a list of the images to load or null if none have been
* selected.
*
* @return list get the list of image descriptors
*/
public List getFrameList() {
List frames = new ArrayList();
List xFrames = this.mcidasxInfo.getFrameNumbers();
if (xFrames.size() < 1) return frames;
for (int i = 0; i < xFrames.size(); i++) {
Integer frmInt = (Integer)xFrames.get(i);
McIdasFrame frame = new McIdasFrame(frmInt.intValue(), this.mcidasxInfo);
frames.add(frame);
}
return frames;
}
/**
* Returns a list of the frame numbers to load or null if none have been
* selected.
*
* @return list get the list of frame numbers
*/
public List getFrameNumbers() {
return this.mcidasxInfo.getFrameNumbers();
}
public int getFrameCount() {
return getFrameNumbers().size();
}
/**
* Load in an ADDE point data set based on the
* <code>PropertyChangeEvent<code>.
*
*/
public void doLoadInThread() {
showWaitCursor();
List frames = getFrameList();
if (frames.size() < 1) {
LogUtil.userMessage("Connection to McIDAS-X Bridge Listener at " + getHost() + ":" + getPort() + " failed");
showNormalCursor();
return;
}
Hashtable ht = new Hashtable();
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.FRAME_NUMBERS_KEY, getFrameNumbers());
if (getFrameCount() > 1) {
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.DATA_NAME_KEY,"Frame Sequence");
} else {
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.DATA_NAME_KEY,"Frame");
}
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.REQUEST_HOST, getHost());
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.REQUEST_PORT, getPort());
ht.put(edu.wisc.ssec.mcidasv.chooser.FrameChooser.REQUEST_KEY, this.mcidasxInfo.getKeyString());
//System.out.println(" ht: " + ht);
makeDataSource("", "MCIDASX", ht);
showNormalCursor();
}
/**
* Make the GUI
*
* @return The GUI
*/
private JLabel statusLabel = new JLabel("Status");
@Override
public void setStatus(String statusString, String foo) {
if (statusString == null)
statusString = "";
statusLabel.setText(statusString);
}
protected JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel hostLabel = McVGuiUtils.makeLabelRight("Host:");
hostLine.setText(mcidasxInfo.getHostString());
McVGuiUtils.setComponentWidth(hostLine, Width.DOUBLE);
hostLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setHost(); }
});
hostLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setHost(); }
});
JLabel portLabel = McVGuiUtils.makeLabelRight("Port:");
portLine.setText(mcidasxInfo.getPortString());
McVGuiUtils.setComponentWidth(portLine, Width.DOUBLE);
portLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setPort(); }
});
portLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setPort(); }
});
JLabel statusLabelLabel = McVGuiUtils.makeLabelRight("");
- statusLabel.setText("Press " + getLoadCommandName() + " to connect to the McIDAS-X Bridge Listener");
+ statusLabel.setText("Press \"" + getLoadCommandName() + "\" to connect to the McIDAS-X Bridge Listener");
McVGuiUtils.setLabelPosition(statusLabel, Position.RIGHT);
McVGuiUtils.setComponentColor(statusLabel, TextColor.STATUS);
JButton helpButton = McVGuiUtils.makeImageButton(ICON_HELP, "Show help");
helpButton.setActionCommand(GuiUtils.CMD_HELP);
helpButton.addActionListener(this);
McVGuiUtils.setComponentWidth(loadButton, Width.DOUBLE);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(hostLabel)
.add(GAP_RELATED)
.add(hostLine))
.add(layout.createSequentialGroup()
.add(portLabel)
.add(GAP_RELATED)
.add(portLine))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(helpButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loadButton))
.add(layout.createSequentialGroup()
.add(statusLabelLabel)
.add(GAP_RELATED)
.add(statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(hostLine)
.add(hostLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(portLine)
.add(portLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusLabelLabel)
.add(statusLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loadButton)
.add(helpButton))
.addContainerGap())
);
return myPanel;
}
}
| true | true | protected JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel hostLabel = McVGuiUtils.makeLabelRight("Host:");
hostLine.setText(mcidasxInfo.getHostString());
McVGuiUtils.setComponentWidth(hostLine, Width.DOUBLE);
hostLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setHost(); }
});
hostLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setHost(); }
});
JLabel portLabel = McVGuiUtils.makeLabelRight("Port:");
portLine.setText(mcidasxInfo.getPortString());
McVGuiUtils.setComponentWidth(portLine, Width.DOUBLE);
portLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setPort(); }
});
portLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setPort(); }
});
JLabel statusLabelLabel = McVGuiUtils.makeLabelRight("");
statusLabel.setText("Press " + getLoadCommandName() + " to connect to the McIDAS-X Bridge Listener");
McVGuiUtils.setLabelPosition(statusLabel, Position.RIGHT);
McVGuiUtils.setComponentColor(statusLabel, TextColor.STATUS);
JButton helpButton = McVGuiUtils.makeImageButton(ICON_HELP, "Show help");
helpButton.setActionCommand(GuiUtils.CMD_HELP);
helpButton.addActionListener(this);
McVGuiUtils.setComponentWidth(loadButton, Width.DOUBLE);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(hostLabel)
.add(GAP_RELATED)
.add(hostLine))
.add(layout.createSequentialGroup()
.add(portLabel)
.add(GAP_RELATED)
.add(portLine))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(helpButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loadButton))
.add(layout.createSequentialGroup()
.add(statusLabelLabel)
.add(GAP_RELATED)
.add(statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(hostLine)
.add(hostLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(portLine)
.add(portLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusLabelLabel)
.add(statusLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loadButton)
.add(helpButton))
.addContainerGap())
);
return myPanel;
}
| protected JComponent doMakeContents() {
JPanel myPanel = new JPanel();
JLabel hostLabel = McVGuiUtils.makeLabelRight("Host:");
hostLine.setText(mcidasxInfo.getHostString());
McVGuiUtils.setComponentWidth(hostLine, Width.DOUBLE);
hostLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setHost(); }
});
hostLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setHost(); }
});
JLabel portLabel = McVGuiUtils.makeLabelRight("Port:");
portLine.setText(mcidasxInfo.getPortString());
McVGuiUtils.setComponentWidth(portLine, Width.DOUBLE);
portLine.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) { setPort(); }
});
portLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { setPort(); }
});
JLabel statusLabelLabel = McVGuiUtils.makeLabelRight("");
statusLabel.setText("Press \"" + getLoadCommandName() + "\" to connect to the McIDAS-X Bridge Listener");
McVGuiUtils.setLabelPosition(statusLabel, Position.RIGHT);
McVGuiUtils.setComponentColor(statusLabel, TextColor.STATUS);
JButton helpButton = McVGuiUtils.makeImageButton(ICON_HELP, "Show help");
helpButton.setActionCommand(GuiUtils.CMD_HELP);
helpButton.addActionListener(this);
McVGuiUtils.setComponentWidth(loadButton, Width.DOUBLE);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(myPanel);
myPanel.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(hostLabel)
.add(GAP_RELATED)
.add(hostLine))
.add(layout.createSequentialGroup()
.add(portLabel)
.add(GAP_RELATED)
.add(portLine))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(helpButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(loadButton))
.add(layout.createSequentialGroup()
.add(statusLabelLabel)
.add(GAP_RELATED)
.add(statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(hostLine)
.add(hostLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(portLine)
.add(portLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(statusLabelLabel)
.add(statusLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(loadButton)
.add(helpButton))
.addContainerGap())
);
return myPanel;
}
|
diff --git a/src/view/PanelSerie.java b/src/view/PanelSerie.java
index 0c6a2df..4b67e20 100644
--- a/src/view/PanelSerie.java
+++ b/src/view/PanelSerie.java
@@ -1,47 +1,46 @@
package view;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListModel;
import controlleur.SerieController;
import model.Serie;
public class PanelSerie extends JPanel{
private static final long serialVersionUID = 1L;
public PanelSerie(){
- JPanel PanelSerie = new JPanel();
//Recuperation des noms de series
ArrayList<String> mesSeries = new ArrayList<String>();
/*SerieController ctrl = new SerieController();
mesSeries = ctrl.getAllSerieName();*/
//Arraylist temporaire
mesSeries.add("Malcom");
mesSeries.add("TBBT");
mesSeries.add("HIMYM");
mesSeries.add("The Simpsons");
//Passage par un defaultListModel
DefaultListModel<String> listModel = new DefaultListModel<>();
for(int i = 0; i <mesSeries.size(); i++){
listModel.addElement(mesSeries.get(i));
}
//Creation et remplissage de la JList
JList listSerie = new JList(listModel);
//Ajout des components
- PanelSerie.add(listSerie);
+ add(listSerie);
}
}
| false | true | public PanelSerie(){
JPanel PanelSerie = new JPanel();
//Recuperation des noms de series
ArrayList<String> mesSeries = new ArrayList<String>();
/*SerieController ctrl = new SerieController();
mesSeries = ctrl.getAllSerieName();*/
//Arraylist temporaire
mesSeries.add("Malcom");
mesSeries.add("TBBT");
mesSeries.add("HIMYM");
mesSeries.add("The Simpsons");
//Passage par un defaultListModel
DefaultListModel<String> listModel = new DefaultListModel<>();
for(int i = 0; i <mesSeries.size(); i++){
listModel.addElement(mesSeries.get(i));
}
//Creation et remplissage de la JList
JList listSerie = new JList(listModel);
//Ajout des components
PanelSerie.add(listSerie);
}
| public PanelSerie(){
//Recuperation des noms de series
ArrayList<String> mesSeries = new ArrayList<String>();
/*SerieController ctrl = new SerieController();
mesSeries = ctrl.getAllSerieName();*/
//Arraylist temporaire
mesSeries.add("Malcom");
mesSeries.add("TBBT");
mesSeries.add("HIMYM");
mesSeries.add("The Simpsons");
//Passage par un defaultListModel
DefaultListModel<String> listModel = new DefaultListModel<>();
for(int i = 0; i <mesSeries.size(); i++){
listModel.addElement(mesSeries.get(i));
}
//Creation et remplissage de la JList
JList listSerie = new JList(listModel);
//Ajout des components
add(listSerie);
}
|
diff --git a/caGrid/projects/sdkQuery41/src/java/style/org/cagrid/data/sdkquery41/style/wizard/config/GeneralConfigurationStep.java b/caGrid/projects/sdkQuery41/src/java/style/org/cagrid/data/sdkquery41/style/wizard/config/GeneralConfigurationStep.java
index 4b6e1319..f5f71dd5 100644
--- a/caGrid/projects/sdkQuery41/src/java/style/org/cagrid/data/sdkquery41/style/wizard/config/GeneralConfigurationStep.java
+++ b/caGrid/projects/sdkQuery41/src/java/style/org/cagrid/data/sdkquery41/style/wizard/config/GeneralConfigurationStep.java
@@ -1,278 +1,276 @@
package org.cagrid.data.sdkquery41.style.wizard.config;
import gov.nih.nci.cagrid.common.JarUtilities;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.common.CastorMappingUtil;
import gov.nih.nci.cagrid.introduce.common.FileFilters;
import gov.nih.nci.cagrid.introduce.common.ServiceInformation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.data.sdkquery41.processor.SDK41QueryProcessor;
import org.cagrid.data.sdkquery41.processor2.SDK41CQL2QueryProcessor;
import org.cagrid.data.sdkquery41.style.common.SDK41StyleConstants;
import org.cagrid.grape.utils.CompositeErrorDialog;
public class GeneralConfigurationStep extends AbstractStyleConfigurationStep {
public static final String GLOBUS_LOCATION_ENV = "GLOBUS_LOCATION";
private static final Log LOG = LogFactory.getLog(GeneralConfigurationStep.class);
private File sdkDirectory = null;
private Properties deployProperties = null;
public GeneralConfigurationStep(ServiceInformation serviceInfo) {
super(serviceInfo);
}
public File getSdkDirectory() {
return sdkDirectory;
}
public void setSdkDirectory(File dir) {
this.sdkDirectory = dir;
// clear the properties
this.deployProperties = null;
}
public void applyConfiguration() throws Exception {
LOG.debug("Applying configuration");
// just in case...
validateSdkDirectory();
// new data service's lib directory
File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib");
File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp");
tempLibDir.mkdir();
String projectName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
File remoteClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "remote-client");
File localClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "local-client");
// wrap up the remote-client config files as a jar file so it'll be on the classpath
// local client stuff might be added by the API Type configuration step
LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system");
File remoteConfigDir = new File(remoteClientDir, "conf");
String remoteConfigJarName = projectName + "-remote-config.jar";
File remoteConfigJar = new File(tempLibDir, remoteConfigJarName);
JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar);
// also jar up the local-client config files
LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system");
File localConfigDir = new File(localClientDir, "conf");
String localConfigJarName = projectName + "-local-config.jar";
File localConfigJar = new File(tempLibDir, localConfigJarName);
JarUtilities.jarDirectory(localConfigDir, localConfigJar);
// set the config jar in the shared configuration
SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar);
SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar);
// get a list of jars found in GLOBUS_LOCATION/lib
File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV));
File globusLib = new File(globusLocation, "lib");
File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter());
Set<String> globusJarNames = new HashSet<String>();
for (File jar : globusJars) {
globusJarNames.add(jar.getName());
}
Set<String> serviceJarNames = new HashSet<String>();
for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) {
serviceJarNames.add(jar.getName());
}
// get the application name
final String applicationName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
// copy in libraries from the remote lib dir that DON'T collide with Globus's
LOG.debug("Copying libraries from remote client directory");
File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter());
for (File lib : remoteLibs) {
String libName = lib.getName();
- if (!globusJarNames.contains(libName)) {
+ if (!globusJarNames.contains(libName) && !libName.startsWith("caGrid-CQL-cql.1.0-")) {
File libOutput = new File(libOutDir, libName);
Utils.copyFile(lib, libOutput);
LOG.debug(libName + " copied to the service");
}
}
LOG.debug("Copying libraries from the local client directory");
File localLibDir = new File(localClientDir, "lib");
File[] localLibs = localLibDir.listFiles();
for (File lib : localLibs) {
String name = lib.getName();
- // is the jar one of the orm, sdk-core, dom4j, or the sdkQuery4 jars that are required?
- boolean ok = name.equals(applicationName + "-orm.jar") || name.equals("sdk-core.jar")
- || name.startsWith("caGrid-sdkQuery4-") || name.equals("dom4j-1.4.jar");
+ boolean ok = true;
+ // is the jar one that is known to conflict with caGrid or Globus?
+ ok = !(name.equals("axis.jar") || name.startsWith("commons-collections")
+ || name.startsWith("commons-logging") || name.startsWith("commons-discovery")
+ || name.startsWith("log4j"));
// is the jar already copied into the service
if (ok && serviceJarNames.contains(name)) {
ok = false;
}
// is the jar one of the caGrid 1.2 jars?
if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) {
- String trimmedName = name.substring(name.length() - 8);
- for (String inService : serviceJarNames) {
- if (inService.startsWith(trimmedName)) {
- ok = false;
- break;
- }
+ if (!name.startsWith("caGrid-sdkQuery4-")) {
+ ok = false;
}
}
// is the jar in the globus lib dir?
if (ok && !globusJarNames.contains(name)) {
File libOutput = new File(libOutDir, name);
Utils.copyFile(lib, libOutput);
LOG.debug(name + " copied to the service");
}
}
// set the application name service property
setCql1ProcessorProperty(
SDK41QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
setCql2ProcessorProperty(
SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
// grab the castor marshalling and unmarshalling xml mapping files
// from the config dir and copy them into the service's package structure
try {
LOG.debug("Copying castor marshalling and unmarshalling files");
File marshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE);
File unmarshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE);
// copy the mapping files to the service's source dir + base package name
String marshallOut = CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation());
String unmarshallOut = CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation());
Utils.copyFile(marshallingMappingFile, new File(marshallOut));
Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut));
} catch (IOException ex) {
ex.printStackTrace();
CompositeErrorDialog.showErrorDialog("Error copying castor mapping files", ex.getMessage(), ex);
}
// set up the shared configuration
SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory());
SharedConfiguration.getInstance().setServiceInfo(getServiceInformation());
SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir());
}
public void validateSdkDirectory() throws Exception {
LOG.debug("Validating the specified caCORE SDK Directory structure");
if (sdkDirectory == null) {
throw new NullPointerException("No SDK directory has been set");
}
// does the directory exist, and is it a directory?
if (!sdkDirectory.exists()) {
throw new FileNotFoundException("Selected SDK directory ( "
+ sdkDirectory.getAbsolutePath() + ") does not exist");
}
if (!sdkDirectory.isDirectory()) {
throw new FileNotFoundException("Selected SDK directory ( "
+ sdkDirectory.getAbsolutePath() + ") is not actually a directory");
}
// the deploy.properties file
Properties sdkProperties = null;
try {
sdkProperties = getDeployPropertiesFromSdkDir();
} catch (IOException ex) {
IOException exception = new IOException(
"Error loading deploy.properties file from the selected SDK directory: "
+ ex.getMessage());
exception.initCause(ex);
throw exception;
}
// the XMI file
File modelsDir = new File(sdkDirectory, "models");
if (!modelsDir.exists() || !modelsDir.isDirectory()) {
throw new FileNotFoundException("Models directory (" + modelsDir.getAbsolutePath() + ") not found");
}
String modelFileName = sdkProperties.getProperty(SDK41StyleConstants.DeployProperties.MODEL_FILE);
File modelFile = new File(modelsDir, modelFileName);
if (!modelFile.exists() || !modelFile.isFile() || !modelFile.canRead()) {
throw new FileNotFoundException("Could not read model file " + modelFile.getName());
}
// output directories
File outputDirectory = new File(sdkDirectory, "output");
String projectName = sdkProperties.getProperty(SDK41StyleConstants.DeployProperties.PROJECT_NAME);
File projectOutputDirectory = new File(outputDirectory, projectName);
if (!projectOutputDirectory.exists() || !projectOutputDirectory.isDirectory()) {
throw new FileNotFoundException("Project output directory (" + projectOutputDirectory.getAbsolutePath() + ") not found");
}
// package directory
File packageDirectory = new File(projectOutputDirectory, "package");
if (!packageDirectory.exists() || !packageDirectory.isDirectory()) {
throw new FileNotFoundException("Project package directory (" + packageDirectory.getAbsolutePath() + ") not found");
}
// local-client
File localClientDir = new File(packageDirectory, "local-client");
if (!localClientDir.exists() || !localClientDir.isDirectory()) {
throw new FileNotFoundException("Local-client directory (" + localClientDir.getAbsolutePath() + ") not found");
}
File localConfDir = new File(localClientDir, "conf");
if (!localConfDir.exists() || !localConfDir.isDirectory()) {
throw new FileNotFoundException("Local-client configuration directory (" + localConfDir.getAbsolutePath() + ") not found");
}
File localLibDir = new File(localClientDir, "lib");
if (!localLibDir.exists() || !localLibDir.isDirectory()) {
throw new FileNotFoundException("Local-client library directory (" + localLibDir.getAbsolutePath() + ") not found");
}
// remote-client
File remoteClientDir = new File(packageDirectory, "remote-client");
if (!remoteClientDir.exists() || !remoteClientDir.isDirectory()) {
throw new FileNotFoundException("Remote-client directory (" + remoteClientDir.getAbsolutePath() + ") not found");
}
File remoteConfDir = new File(remoteClientDir, "conf");
if (!remoteClientDir.exists() || !remoteConfDir.isDirectory()) {
throw new FileNotFoundException("Remote-client configuration directory (" + remoteConfDir.getAbsolutePath() + ") not found");
}
File remoteLibDir = new File(remoteClientDir, "lib");
if (!remoteLibDir.exists() || !remoteLibDir.exists()) {
throw new FileNotFoundException("Remote-client library directory (" + remoteLibDir.getAbsolutePath() + ") not found");
}
}
public Properties getDeployPropertiesFromSdkDir() throws IOException {
if (this.deployProperties == null) {
LOG.debug("Loading deploy.properties file");
File propertiesFile = getDeployPropertiesFile();
deployProperties = new Properties();
FileInputStream fis = new FileInputStream(propertiesFile);
deployProperties.load(fis);
fis.close();
}
return deployProperties;
}
public File getDeployPropertiesFile() {
if (sdkDirectory != null) {
File propertiesFile = new File(sdkDirectory, "conf" + File.separator + SDK41StyleConstants.DEPLOY_PROPERTIES_FILENAME);
return propertiesFile;
}
return null;
}
}
| false | true | public void applyConfiguration() throws Exception {
LOG.debug("Applying configuration");
// just in case...
validateSdkDirectory();
// new data service's lib directory
File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib");
File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp");
tempLibDir.mkdir();
String projectName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
File remoteClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "remote-client");
File localClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "local-client");
// wrap up the remote-client config files as a jar file so it'll be on the classpath
// local client stuff might be added by the API Type configuration step
LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system");
File remoteConfigDir = new File(remoteClientDir, "conf");
String remoteConfigJarName = projectName + "-remote-config.jar";
File remoteConfigJar = new File(tempLibDir, remoteConfigJarName);
JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar);
// also jar up the local-client config files
LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system");
File localConfigDir = new File(localClientDir, "conf");
String localConfigJarName = projectName + "-local-config.jar";
File localConfigJar = new File(tempLibDir, localConfigJarName);
JarUtilities.jarDirectory(localConfigDir, localConfigJar);
// set the config jar in the shared configuration
SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar);
SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar);
// get a list of jars found in GLOBUS_LOCATION/lib
File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV));
File globusLib = new File(globusLocation, "lib");
File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter());
Set<String> globusJarNames = new HashSet<String>();
for (File jar : globusJars) {
globusJarNames.add(jar.getName());
}
Set<String> serviceJarNames = new HashSet<String>();
for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) {
serviceJarNames.add(jar.getName());
}
// get the application name
final String applicationName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
// copy in libraries from the remote lib dir that DON'T collide with Globus's
LOG.debug("Copying libraries from remote client directory");
File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter());
for (File lib : remoteLibs) {
String libName = lib.getName();
if (!globusJarNames.contains(libName)) {
File libOutput = new File(libOutDir, libName);
Utils.copyFile(lib, libOutput);
LOG.debug(libName + " copied to the service");
}
}
LOG.debug("Copying libraries from the local client directory");
File localLibDir = new File(localClientDir, "lib");
File[] localLibs = localLibDir.listFiles();
for (File lib : localLibs) {
String name = lib.getName();
// is the jar one of the orm, sdk-core, dom4j, or the sdkQuery4 jars that are required?
boolean ok = name.equals(applicationName + "-orm.jar") || name.equals("sdk-core.jar")
|| name.startsWith("caGrid-sdkQuery4-") || name.equals("dom4j-1.4.jar");
// is the jar already copied into the service
if (ok && serviceJarNames.contains(name)) {
ok = false;
}
// is the jar one of the caGrid 1.2 jars?
if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) {
String trimmedName = name.substring(name.length() - 8);
for (String inService : serviceJarNames) {
if (inService.startsWith(trimmedName)) {
ok = false;
break;
}
}
}
// is the jar in the globus lib dir?
if (ok && !globusJarNames.contains(name)) {
File libOutput = new File(libOutDir, name);
Utils.copyFile(lib, libOutput);
LOG.debug(name + " copied to the service");
}
}
// set the application name service property
setCql1ProcessorProperty(
SDK41QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
setCql2ProcessorProperty(
SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
// grab the castor marshalling and unmarshalling xml mapping files
// from the config dir and copy them into the service's package structure
try {
LOG.debug("Copying castor marshalling and unmarshalling files");
File marshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE);
File unmarshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE);
// copy the mapping files to the service's source dir + base package name
String marshallOut = CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation());
String unmarshallOut = CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation());
Utils.copyFile(marshallingMappingFile, new File(marshallOut));
Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut));
} catch (IOException ex) {
ex.printStackTrace();
CompositeErrorDialog.showErrorDialog("Error copying castor mapping files", ex.getMessage(), ex);
}
// set up the shared configuration
SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory());
SharedConfiguration.getInstance().setServiceInfo(getServiceInformation());
SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir());
}
| public void applyConfiguration() throws Exception {
LOG.debug("Applying configuration");
// just in case...
validateSdkDirectory();
// new data service's lib directory
File libOutDir = new File(getServiceInformation().getBaseDirectory(), "lib");
File tempLibDir = new File(getServiceInformation().getBaseDirectory(), "temp");
tempLibDir.mkdir();
String projectName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
File remoteClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "remote-client");
File localClientDir = new File(sdkDirectory,
"output" + File.separator + projectName + File.separator +
"package" + File.separator + "local-client");
// wrap up the remote-client config files as a jar file so it'll be on the classpath
// local client stuff might be added by the API Type configuration step
LOG.debug("Creating a jar to contain the remote configuration of the caCORE SDK system");
File remoteConfigDir = new File(remoteClientDir, "conf");
String remoteConfigJarName = projectName + "-remote-config.jar";
File remoteConfigJar = new File(tempLibDir, remoteConfigJarName);
JarUtilities.jarDirectory(remoteConfigDir, remoteConfigJar);
// also jar up the local-client config files
LOG.debug("Creating a jar to contain the local configuration of the caCORE SDK system");
File localConfigDir = new File(localClientDir, "conf");
String localConfigJarName = projectName + "-local-config.jar";
File localConfigJar = new File(tempLibDir, localConfigJarName);
JarUtilities.jarDirectory(localConfigDir, localConfigJar);
// set the config jar in the shared configuration
SharedConfiguration.getInstance().setRemoteConfigJarFile(remoteConfigJar);
SharedConfiguration.getInstance().setLocalConfigJarFile(localConfigJar);
// get a list of jars found in GLOBUS_LOCATION/lib
File globusLocation = new File(System.getenv(GLOBUS_LOCATION_ENV));
File globusLib = new File(globusLocation, "lib");
File[] globusJars = globusLib.listFiles(new FileFilters.JarFileFilter());
Set<String> globusJarNames = new HashSet<String>();
for (File jar : globusJars) {
globusJarNames.add(jar.getName());
}
Set<String> serviceJarNames = new HashSet<String>();
for (File jar : libOutDir.listFiles(new FileFilters.JarFileFilter())) {
serviceJarNames.add(jar.getName());
}
// get the application name
final String applicationName = getDeployPropertiesFromSdkDir().getProperty(
SDK41StyleConstants.DeployProperties.PROJECT_NAME);
// copy in libraries from the remote lib dir that DON'T collide with Globus's
LOG.debug("Copying libraries from remote client directory");
File[] remoteLibs = new File(remoteClientDir, "lib").listFiles(new FileFilters.JarFileFilter());
for (File lib : remoteLibs) {
String libName = lib.getName();
if (!globusJarNames.contains(libName) && !libName.startsWith("caGrid-CQL-cql.1.0-")) {
File libOutput = new File(libOutDir, libName);
Utils.copyFile(lib, libOutput);
LOG.debug(libName + " copied to the service");
}
}
LOG.debug("Copying libraries from the local client directory");
File localLibDir = new File(localClientDir, "lib");
File[] localLibs = localLibDir.listFiles();
for (File lib : localLibs) {
String name = lib.getName();
boolean ok = true;
// is the jar one that is known to conflict with caGrid or Globus?
ok = !(name.equals("axis.jar") || name.startsWith("commons-collections")
|| name.startsWith("commons-logging") || name.startsWith("commons-discovery")
|| name.startsWith("log4j"));
// is the jar already copied into the service
if (ok && serviceJarNames.contains(name)) {
ok = false;
}
// is the jar one of the caGrid 1.2 jars?
if (ok && name.startsWith("caGrid-") && name.endsWith("-1.2.jar")) {
if (!name.startsWith("caGrid-sdkQuery4-")) {
ok = false;
}
}
// is the jar in the globus lib dir?
if (ok && !globusJarNames.contains(name)) {
File libOutput = new File(libOutDir, name);
Utils.copyFile(lib, libOutput);
LOG.debug(name + " copied to the service");
}
}
// set the application name service property
setCql1ProcessorProperty(
SDK41QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
setCql2ProcessorProperty(
SDK41CQL2QueryProcessor.PROPERTY_APPLICATION_NAME,
applicationName, false);
// grab the castor marshalling and unmarshalling xml mapping files
// from the config dir and copy them into the service's package structure
try {
LOG.debug("Copying castor marshalling and unmarshalling files");
File marshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_MARSHALLING_MAPPING_FILE);
File unmarshallingMappingFile =
new File(remoteConfigDir, CastorMappingUtil.CASTOR_UNMARSHALLING_MAPPING_FILE);
// copy the mapping files to the service's source dir + base package name
String marshallOut = CastorMappingUtil.getMarshallingCastorMappingFileName(getServiceInformation());
String unmarshallOut = CastorMappingUtil.getUnmarshallingCastorMappingFileName(getServiceInformation());
Utils.copyFile(marshallingMappingFile, new File(marshallOut));
Utils.copyFile(unmarshallingMappingFile, new File(unmarshallOut));
} catch (IOException ex) {
ex.printStackTrace();
CompositeErrorDialog.showErrorDialog("Error copying castor mapping files", ex.getMessage(), ex);
}
// set up the shared configuration
SharedConfiguration.getInstance().setSdkDirectory(getSdkDirectory());
SharedConfiguration.getInstance().setServiceInfo(getServiceInformation());
SharedConfiguration.getInstance().setSdkDeployProperties(getDeployPropertiesFromSdkDir());
}
|
diff --git a/src/main/java/net/robbytu/banjoserver/bungee/bans/BanCommand.java b/src/main/java/net/robbytu/banjoserver/bungee/bans/BanCommand.java
index 8be4719..3647870 100644
--- a/src/main/java/net/robbytu/banjoserver/bungee/bans/BanCommand.java
+++ b/src/main/java/net/robbytu/banjoserver/bungee/bans/BanCommand.java
@@ -1,41 +1,41 @@
package net.robbytu.banjoserver.bungee.bans;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;
public class BanCommand extends Command {
private final String usage = "/ban [user] [reason]";
public BanCommand() {
super("ban");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("bs.admin")) {
this.failCommand(sender, "You do not have permission to execute this command.");
return;
}
if(args.length < 2) {
this.failCommand(sender, "Missing arguments.");
return;
}
String reasonBody = "";
- for (int i = 0; i < args.length - 1; i++) reasonBody += args[i];
+ for (int i = 1; i < args.length; i++) reasonBody += ((args.length == 0) ? "" : " ") + args[i];
Ban ban = new Ban();
ban.username = args[0];
ban.reason = reasonBody;
ban.mod = sender.getName();
Bans.banUser(ban);
}
private void failCommand(CommandSender sender, String message) {
sender.sendMessage(ChatColor.RED + message);
sender.sendMessage(ChatColor.GRAY + "Usage: " + ChatColor.ITALIC + this.usage);
}
}
| true | true | public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("bs.admin")) {
this.failCommand(sender, "You do not have permission to execute this command.");
return;
}
if(args.length < 2) {
this.failCommand(sender, "Missing arguments.");
return;
}
String reasonBody = "";
for (int i = 0; i < args.length - 1; i++) reasonBody += args[i];
Ban ban = new Ban();
ban.username = args[0];
ban.reason = reasonBody;
ban.mod = sender.getName();
Bans.banUser(ban);
}
| public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("bs.admin")) {
this.failCommand(sender, "You do not have permission to execute this command.");
return;
}
if(args.length < 2) {
this.failCommand(sender, "Missing arguments.");
return;
}
String reasonBody = "";
for (int i = 1; i < args.length; i++) reasonBody += ((args.length == 0) ? "" : " ") + args[i];
Ban ban = new Ban();
ban.username = args[0];
ban.reason = reasonBody;
ban.mod = sender.getName();
Bans.banUser(ban);
}
|
diff --git a/src/geneticalgorithm/RunAG.java b/src/geneticalgorithm/RunAG.java
index 060ec26..7588187 100644
--- a/src/geneticalgorithm/RunAG.java
+++ b/src/geneticalgorithm/RunAG.java
@@ -1,215 +1,215 @@
/*
* Copyright 2012 Anderson Queiroz <contato(at)andersonq(dot)eti(dot)br>
* Fernando Zucatelli, João Coutinho, Tiago Queiroz <contato(at)tiago(dot)eti(dot)br>
*
* 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 geneticalgorithm;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import geneticalgorithm.Chromosome;
import geneticalgorithm.CompMaximize;
import geneticalgorithm.CompMinimize;
/**
*
* @author Anderson Queiroz, Fernando Zucatelli, João Coutinho, Tiago Queiroz
*
*/
public class RunAG
{
/**
* @param args
*/
public static void main(String[] args)
{
double mutation = 0.05;
double elitep = 0.10;
double txcross = 0;
int pop = -50;
int cycles = -50;
int i, k;
int elite = -1;
int op = 100;
Chromosome o_pop[], n_pop[], tmp[];
Scanner sc = new Scanner(System.in);
Comparator<Chromosome> comp = null;
/* Seting up variables */
mutation=-1; elitep=-1; txcross=-1; cycles=-1;
while (txcross < 0.0 || txcross > 1.0)
{
System.out.printf("\nEscolha a taxa de crossover, inteiro de 0 a 100 : ");
txcross = sc.nextInt()/100.0;
}
while (mutation < 0.0 || mutation > 1.0)
{
System.out.printf("\nEscolha a taxa de mutacao, inteiro de 0 a 100 : ");
mutation = sc.nextInt()/100.0;
}
while (elitep < 0.0 || elitep > 1.0)
{
System.out.printf("\nEscolha a taxa de elitismo, inteiro de 0 a 100 : ");
elitep = sc.nextInt()/100.0;
}
while (pop < 0 || pop > Integer.MAX_VALUE)
{
System.out.printf("\nEscolha o tamanho da população, inteiro de 1 a %d: ", Integer.MAX_VALUE);
pop = sc.nextInt();
}
System.out.print("\nEscolha o número de bits do cromossomo: ");
Chromosome.setBITS(sc.nextInt());
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
switch(op)
{
case 1:
while (cycles < 1)
{
comp = new CompMaximize();
System.out.printf("\nMaximizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
case 2:
while (cycles < 1)
{
comp = new CompMinimize();
System.out.printf("\n\nMinimizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
default:
while (op != 1 || op != 2)
{
System.out.println("Opção " + op + "inválida, por favor escolha:");
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
}
break;
}
/* End set up variables */
/* Starting Algorithm */
elite = (int) Math.floor(pop*(elitep));
o_pop = new Chromosome[pop];
n_pop = new Chromosome[pop];
- System.out.println("Function to maximize: f(x) = -(x-1)^2 +5");
+ System.out.println("Function: f(x) = -(x-1)^2 +5");
for(int x = -10; x < 21; x++)
System.out.printf("f(%d) = %f\n", x, -1.0*Math.pow(x-1.0, 2.0)+5.0);
System.out.printf("Initializing....\n");
for(i = 0; i < pop; i++)
{
o_pop[i] = new Chromosome();
System.out.printf("[%d] %s: %f\n", i, o_pop[i], o_pop[i].getValue());
}
for(i = 0; i < cycles; i++)
{
System.out.printf("==================Generation %d==================\n", i);
/* Evaluate */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
/* Put the elite in the new population vector */
System.out.println("População:");
for(k = 0; k < elite; k++)
{
n_pop[k] = o_pop[k];
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
}
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Do a contest */
tmp = Chromosome.contest(o_pop, (pop-elite), 5, comp);
/* Put the result of the contest in n_pop */
for(k = 0; k < pop-elite; k++)
{
//Apply crossover, or not
if(Math.random() <= txcross)
n_pop[k+elite] = tmp[k];
else
n_pop[k+elite] = o_pop[k+elite];
}
/* Mutate */
for(k=elite; k < pop; k++)
n_pop[k].mutation(mutation);
o_pop = n_pop;
System.out.flush();
}
/* Evaluate the last population */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
System.out.println("\n\nTerminado!\n");
System.out.println("A última população é: ");
/* Put the elite in the new population vector */
for(k = 0; k < elite; k++)
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
System.out.println("\n\nA melhor solução é:\n");
System.out.printf("f(%f) = %f\nChromossomo: %s\n", o_pop[0].getValue(), o_pop[0].getRank(), o_pop[0]);
}
public static double evaluate(Chromosome c)
{
double v, x = c.getValue();
v = -1.0*Math.pow(x-1.0, 2.0)+5.0; //it's f(x) = -(x-1)^2 +5
return v;
}
}
| true | true | public static void main(String[] args)
{
double mutation = 0.05;
double elitep = 0.10;
double txcross = 0;
int pop = -50;
int cycles = -50;
int i, k;
int elite = -1;
int op = 100;
Chromosome o_pop[], n_pop[], tmp[];
Scanner sc = new Scanner(System.in);
Comparator<Chromosome> comp = null;
/* Seting up variables */
mutation=-1; elitep=-1; txcross=-1; cycles=-1;
while (txcross < 0.0 || txcross > 1.0)
{
System.out.printf("\nEscolha a taxa de crossover, inteiro de 0 a 100 : ");
txcross = sc.nextInt()/100.0;
}
while (mutation < 0.0 || mutation > 1.0)
{
System.out.printf("\nEscolha a taxa de mutacao, inteiro de 0 a 100 : ");
mutation = sc.nextInt()/100.0;
}
while (elitep < 0.0 || elitep > 1.0)
{
System.out.printf("\nEscolha a taxa de elitismo, inteiro de 0 a 100 : ");
elitep = sc.nextInt()/100.0;
}
while (pop < 0 || pop > Integer.MAX_VALUE)
{
System.out.printf("\nEscolha o tamanho da população, inteiro de 1 a %d: ", Integer.MAX_VALUE);
pop = sc.nextInt();
}
System.out.print("\nEscolha o número de bits do cromossomo: ");
Chromosome.setBITS(sc.nextInt());
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
switch(op)
{
case 1:
while (cycles < 1)
{
comp = new CompMaximize();
System.out.printf("\nMaximizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
case 2:
while (cycles < 1)
{
comp = new CompMinimize();
System.out.printf("\n\nMinimizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
default:
while (op != 1 || op != 2)
{
System.out.println("Opção " + op + "inválida, por favor escolha:");
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
}
break;
}
/* End set up variables */
/* Starting Algorithm */
elite = (int) Math.floor(pop*(elitep));
o_pop = new Chromosome[pop];
n_pop = new Chromosome[pop];
System.out.println("Function to maximize: f(x) = -(x-1)^2 +5");
for(int x = -10; x < 21; x++)
System.out.printf("f(%d) = %f\n", x, -1.0*Math.pow(x-1.0, 2.0)+5.0);
System.out.printf("Initializing....\n");
for(i = 0; i < pop; i++)
{
o_pop[i] = new Chromosome();
System.out.printf("[%d] %s: %f\n", i, o_pop[i], o_pop[i].getValue());
}
for(i = 0; i < cycles; i++)
{
System.out.printf("==================Generation %d==================\n", i);
/* Evaluate */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
/* Put the elite in the new population vector */
System.out.println("População:");
for(k = 0; k < elite; k++)
{
n_pop[k] = o_pop[k];
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
}
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Do a contest */
tmp = Chromosome.contest(o_pop, (pop-elite), 5, comp);
/* Put the result of the contest in n_pop */
for(k = 0; k < pop-elite; k++)
{
//Apply crossover, or not
if(Math.random() <= txcross)
n_pop[k+elite] = tmp[k];
else
n_pop[k+elite] = o_pop[k+elite];
}
/* Mutate */
for(k=elite; k < pop; k++)
n_pop[k].mutation(mutation);
o_pop = n_pop;
System.out.flush();
}
/* Evaluate the last population */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
System.out.println("\n\nTerminado!\n");
System.out.println("A última população é: ");
/* Put the elite in the new population vector */
for(k = 0; k < elite; k++)
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
System.out.println("\n\nA melhor solução é:\n");
System.out.printf("f(%f) = %f\nChromossomo: %s\n", o_pop[0].getValue(), o_pop[0].getRank(), o_pop[0]);
}
| public static void main(String[] args)
{
double mutation = 0.05;
double elitep = 0.10;
double txcross = 0;
int pop = -50;
int cycles = -50;
int i, k;
int elite = -1;
int op = 100;
Chromosome o_pop[], n_pop[], tmp[];
Scanner sc = new Scanner(System.in);
Comparator<Chromosome> comp = null;
/* Seting up variables */
mutation=-1; elitep=-1; txcross=-1; cycles=-1;
while (txcross < 0.0 || txcross > 1.0)
{
System.out.printf("\nEscolha a taxa de crossover, inteiro de 0 a 100 : ");
txcross = sc.nextInt()/100.0;
}
while (mutation < 0.0 || mutation > 1.0)
{
System.out.printf("\nEscolha a taxa de mutacao, inteiro de 0 a 100 : ");
mutation = sc.nextInt()/100.0;
}
while (elitep < 0.0 || elitep > 1.0)
{
System.out.printf("\nEscolha a taxa de elitismo, inteiro de 0 a 100 : ");
elitep = sc.nextInt()/100.0;
}
while (pop < 0 || pop > Integer.MAX_VALUE)
{
System.out.printf("\nEscolha o tamanho da população, inteiro de 1 a %d: ", Integer.MAX_VALUE);
pop = sc.nextInt();
}
System.out.print("\nEscolha o número de bits do cromossomo: ");
Chromosome.setBITS(sc.nextInt());
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
switch(op)
{
case 1:
while (cycles < 1)
{
comp = new CompMaximize();
System.out.printf("\nMaximizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
case 2:
while (cycles < 1)
{
comp = new CompMinimize();
System.out.printf("\n\nMinimizar funcao escolhido");
System.out.printf("\nQuantos ciclos rodar: ");
cycles = sc.nextInt();
}
break;
default:
while (op != 1 || op != 2)
{
System.out.println("Opção " + op + "inválida, por favor escolha:");
System.out.printf("0 - Sair\n");
System.out.printf("1 - Maximizar funcao\n");
System.out.printf("2 - Minimizar funcao\n");
System.out.printf("> ");
op = sc.nextInt();
}
break;
}
/* End set up variables */
/* Starting Algorithm */
elite = (int) Math.floor(pop*(elitep));
o_pop = new Chromosome[pop];
n_pop = new Chromosome[pop];
System.out.println("Function: f(x) = -(x-1)^2 +5");
for(int x = -10; x < 21; x++)
System.out.printf("f(%d) = %f\n", x, -1.0*Math.pow(x-1.0, 2.0)+5.0);
System.out.printf("Initializing....\n");
for(i = 0; i < pop; i++)
{
o_pop[i] = new Chromosome();
System.out.printf("[%d] %s: %f\n", i, o_pop[i], o_pop[i].getValue());
}
for(i = 0; i < cycles; i++)
{
System.out.printf("==================Generation %d==================\n", i);
/* Evaluate */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
/* Put the elite in the new population vector */
System.out.println("População:");
for(k = 0; k < elite; k++)
{
n_pop[k] = o_pop[k];
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
}
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Do a contest */
tmp = Chromosome.contest(o_pop, (pop-elite), 5, comp);
/* Put the result of the contest in n_pop */
for(k = 0; k < pop-elite; k++)
{
//Apply crossover, or not
if(Math.random() <= txcross)
n_pop[k+elite] = tmp[k];
else
n_pop[k+elite] = o_pop[k+elite];
}
/* Mutate */
for(k=elite; k < pop; k++)
n_pop[k].mutation(mutation);
o_pop = n_pop;
System.out.flush();
}
/* Evaluate the last population */
for(k = 0; k < pop; k++)
o_pop[k].setRank(evaluate(o_pop[k]));
/* Sort the vector using Rank*/
Arrays.sort(o_pop, comp);
System.out.println("\n\nTerminado!\n");
System.out.println("A última população é: ");
/* Put the elite in the new population vector */
for(k = 0; k < elite; k++)
System.out.printf("Elite[%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
/* Print everyone */
for(k = elite; k < pop; k++)
System.out.printf(" [%d] = f(%f) = %f {%s}\n", k, o_pop[k].getValue(), o_pop[k].getRank(), o_pop[k]);
System.out.println("\n\nA melhor solução é:\n");
System.out.printf("f(%f) = %f\nChromossomo: %s\n", o_pop[0].getValue(), o_pop[0].getRank(), o_pop[0]);
}
|
diff --git a/src/q4/Client2.java b/src/q4/Client2.java
index a595c63..aa161ed 100644
--- a/src/q4/Client2.java
+++ b/src/q4/Client2.java
@@ -1,131 +1,131 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Client2 {
protected static DatagramSocket sock;
protected static InetAddress addr;
protected static int port;
protected static String port2;
private static String clientId;
protected Client2() {
}
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: <Server Address> <Port>");
System.exit(1);
}
try {
addr = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} catch (UnknownHostException e) {
System.err.println("Invalid hostname.");
e.printStackTrace();
}
/* Create socket; connect to given server */
sock = new DatagramSocket();
sock.connect(addr, port);
/* Greet server */
byte[] g = "GREETING2".getBytes();
DatagramPacket greetingPacket = new DatagramPacket(g, g.length, addr, port);
sock.send(greetingPacket);
/* get client id from server */
byte[] data = new byte[1024];
DatagramPacket pack = new DatagramPacket(data, data.length);
sock.receive(pack);
String msg = new String(pack.getData());
clientId = msg;
System.out.println("Received Client ID: " + clientId);
/* get port from server */
sock.receive(pack);
- port2 = new String(pack.getData());
+ port2 = new String(pack.getData()).trim();
System.out.println("Recv Port: " + port2);
String s = null;
try {
Process p = Runtime.getRuntime().exec("/usr/bin/ssh -R " + port2 + ":localhost:22 jumpbug.ccs.neu.edu");
System.out.print("Reverse SSH running" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
System.err.println("(22) Could not send packet.");
e.printStackTrace();
}
/* Create thread */
Client2 client = new Client2();
Thread listenThread = new Thread(client.new ClientListener());
listenThread.start();
client.heartbeat();
}
protected void heartbeat() throws IOException {
while (true) {
String hb;
try {
hb = "HEARTBEAT" + clientId;
byte[] hbmsg = hb.getBytes();
DatagramPacket messagePacket = new DatagramPacket(hbmsg,
hbmsg.length, addr, port);
sock.send(messagePacket);
Thread.currentThread().sleep(10000); /* sleep for 10 sec. */
System.out.println("Sent hearbeat\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected class ClientListener implements Runnable {
protected ClientListener() {
}
@Override
public void run() {
byte[] data = new byte[1024];
DatagramPacket pack = new DatagramPacket(data, data.length);
try {
while (true) {
sock.receive(pack);
String msg = new String(data);
/* TODO: Parse message; open connection*/
if (msg.startsWith("RECONNECT")) {
System.out.println(msg);
Process p = Runtime.getRuntime().exec("ssh -R " + port2 + ":localhost:22 [email protected]");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| true | true | public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: <Server Address> <Port>");
System.exit(1);
}
try {
addr = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} catch (UnknownHostException e) {
System.err.println("Invalid hostname.");
e.printStackTrace();
}
/* Create socket; connect to given server */
sock = new DatagramSocket();
sock.connect(addr, port);
/* Greet server */
byte[] g = "GREETING2".getBytes();
DatagramPacket greetingPacket = new DatagramPacket(g, g.length, addr, port);
sock.send(greetingPacket);
/* get client id from server */
byte[] data = new byte[1024];
DatagramPacket pack = new DatagramPacket(data, data.length);
sock.receive(pack);
String msg = new String(pack.getData());
clientId = msg;
System.out.println("Received Client ID: " + clientId);
/* get port from server */
sock.receive(pack);
port2 = new String(pack.getData());
System.out.println("Recv Port: " + port2);
String s = null;
try {
Process p = Runtime.getRuntime().exec("/usr/bin/ssh -R " + port2 + ":localhost:22 jumpbug.ccs.neu.edu");
System.out.print("Reverse SSH running" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
System.err.println("(22) Could not send packet.");
e.printStackTrace();
}
/* Create thread */
Client2 client = new Client2();
Thread listenThread = new Thread(client.new ClientListener());
listenThread.start();
client.heartbeat();
}
| public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Usage: <Server Address> <Port>");
System.exit(1);
}
try {
addr = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
} catch (UnknownHostException e) {
System.err.println("Invalid hostname.");
e.printStackTrace();
}
/* Create socket; connect to given server */
sock = new DatagramSocket();
sock.connect(addr, port);
/* Greet server */
byte[] g = "GREETING2".getBytes();
DatagramPacket greetingPacket = new DatagramPacket(g, g.length, addr, port);
sock.send(greetingPacket);
/* get client id from server */
byte[] data = new byte[1024];
DatagramPacket pack = new DatagramPacket(data, data.length);
sock.receive(pack);
String msg = new String(pack.getData());
clientId = msg;
System.out.println("Received Client ID: " + clientId);
/* get port from server */
sock.receive(pack);
port2 = new String(pack.getData()).trim();
System.out.println("Recv Port: " + port2);
String s = null;
try {
Process p = Runtime.getRuntime().exec("/usr/bin/ssh -R " + port2 + ":localhost:22 jumpbug.ccs.neu.edu");
System.out.print("Reverse SSH running" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
System.err.println("(22) Could not send packet.");
e.printStackTrace();
}
/* Create thread */
Client2 client = new Client2();
Thread listenThread = new Thread(client.new ClientListener());
listenThread.start();
client.heartbeat();
}
|
diff --git a/src/com/tistory/devyongsik/config/CollectionConfig.java b/src/com/tistory/devyongsik/config/CollectionConfig.java
index 0bf2894..5c6dafd 100644
--- a/src/com/tistory/devyongsik/config/CollectionConfig.java
+++ b/src/com/tistory/devyongsik/config/CollectionConfig.java
@@ -1,151 +1,151 @@
package com.tistory.devyongsik.config;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tistory.devyongsik.domain.Collection;
import com.tistory.devyongsik.domain.CollectionField;
/**
* author : need4spd, [email protected], 2012. 2. 26.
*/
public class CollectionConfig {
private Logger logger = LoggerFactory.getLogger(CollectionConfig.class);
private final String DEFAULT_CONFIG_XML = "collection/collections.xml";
private Map<String, Collection> collections = new HashMap<String, Collection>();
private static CollectionConfig instance = new CollectionConfig();
public static CollectionConfig getInstance() {
return instance;
}
public Collection getCollection(String collectionName) {
return collections.get(collectionName);
}
public Map<String, Collection> getCollections() {
return collections;
}
private CollectionConfig() {
logger.info("start init Collection Configs.");
initProperty();
}
private void initProperty() {
ResourceLoader resourceLoader = new ResourceLoader(DEFAULT_CONFIG_XML);
Document document = resourceLoader.getDocument();
//get collection list
@SuppressWarnings("unchecked")
List<Element> collectionList = document.selectNodes("//collection");
logger.debug("collectionList : {}", collectionList.toString());
for(Element node : collectionList) {
Collection collection = new Collection();
logger.debug("indexingDirectory : {}", node.elementText("indexingDirectory"));
- logger.debug("name : {}", node.elementText("name"));
+ logger.debug("name : {}", node.attributeValue("name"));
collection.setIndexingDir(node.elementText("indexingDirectory"));
- collection.setCollectionName(node.elementText("name"));
+ collection.setCollectionName(node.attributeValue("name"));
@SuppressWarnings("unchecked")
- List<Element> fieldsList = node.selectNodes("field");
+ List<Element> fieldsList = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"/fields/field");
if(logger.isDebugEnabled()) {
for(Element e : fieldsList) {
logger.debug("field name : {}", e.attributeValue("name"));
logger.debug("field store : {}", e.attributeValue("store"));
logger.debug("field index : {}", e.attributeValue("index"));
logger.debug("field type : {}", e.attributeValue("type"));
logger.debug("field analyze : {}", e.attributeValue("analyze"));
logger.debug("field must : {}", e.attributeValue("must"));
logger.debug("field boost : {}", e.attributeValue("boost"));
logger.debug("field termposition : {}", e.attributeValue("termposition"));
logger.debug("field termoffset : {}", e.attributeValue("termoffset"));
}
}
for(Element e : fieldsList) {
CollectionField collectionField = new CollectionField();
collectionField.setName(e.attributeValue("name"));
collectionField.setisStore(Boolean.valueOf(e.attributeValue("store")));
collectionField.setisIndexing(Boolean.valueOf(e.attributeValue("index")));
collectionField.setType(e.attributeValue("type"));
collectionField.setisAnalyze(Boolean.valueOf(e.attributeValue("analyze")));
collectionField.setisMust(Boolean.valueOf(e.attributeValue("must")));
collectionField.setFieldBoost(Float.parseFloat(StringUtils.defaultString(e.attributeValue("boost"), "0")));
collectionField.setHasTermOffset(Boolean.valueOf(e.attributeValue("termoffset")));
collectionField.setHasTermPosition(Boolean.valueOf(e.attributeValue("termposition")));
collectionField.setHasTermVector(Boolean.valueOf(e.attributeValue("termvector")));
collection.putField(collectionField.getName(), collectionField);
collection.addFieldName(collectionField.getName());
}
@SuppressWarnings("unchecked")
- List<Element> defaultSearchFields = node.selectNodes("//defaultSearchField");
+ List<Element> defaultSearchFields = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"//defaultSearchFields/defaultSearchField");
if(logger.isDebugEnabled()) {
for(Element e : defaultSearchFields) {
logger.debug("default search fields : {}", e.attributeValue("name"));
}
}
for(Element e : defaultSearchFields) {
collection.addDefaultSearchFieldNames(e.attributeValue("name"));
}
@SuppressWarnings("unchecked")
- List<Element> sortFields = node.selectNodes("//sortField");
+ List<Element> sortFields = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"//sortFields/sortField");
if(logger.isDebugEnabled()) {
for(Element e : sortFields) {
logger.debug("sortField source : {}", e.attributeValue("source"));
logger.debug("sortField dest : {}", e.attributeValue("dest"));
}
}
for(Element e : sortFields) {
String srcFieldName = e.attributeValue("source");
CollectionField srcField = collection.getFieldsByName().get(srcFieldName);
if(srcField == null) {
throw new IllegalStateException("정렬 필드 설정에 필요한 원본(source) 필드가 없습니다.");
}
try {
String dstFieldName = e.attributeValue("dest");
CollectionField dstField = (CollectionField) srcField.clone();
dstField.setisAnalyze(false);
dstField.setisIndexing(true);
dstField.setName(dstFieldName);
collection.putField(dstFieldName, dstField);
collection.addSortFieldNames(dstFieldName);
} catch (CloneNotSupportedException e1) {
logger.error("error : ", e1);
}
}
collections.put(collection.getCollectionName(), collection);
}// end for(Element node : collectionList)
logger.debug("collections : {}", collections);
}
}
| false | true | private void initProperty() {
ResourceLoader resourceLoader = new ResourceLoader(DEFAULT_CONFIG_XML);
Document document = resourceLoader.getDocument();
//get collection list
@SuppressWarnings("unchecked")
List<Element> collectionList = document.selectNodes("//collection");
logger.debug("collectionList : {}", collectionList.toString());
for(Element node : collectionList) {
Collection collection = new Collection();
logger.debug("indexingDirectory : {}", node.elementText("indexingDirectory"));
logger.debug("name : {}", node.elementText("name"));
collection.setIndexingDir(node.elementText("indexingDirectory"));
collection.setCollectionName(node.elementText("name"));
@SuppressWarnings("unchecked")
List<Element> fieldsList = node.selectNodes("field");
if(logger.isDebugEnabled()) {
for(Element e : fieldsList) {
logger.debug("field name : {}", e.attributeValue("name"));
logger.debug("field store : {}", e.attributeValue("store"));
logger.debug("field index : {}", e.attributeValue("index"));
logger.debug("field type : {}", e.attributeValue("type"));
logger.debug("field analyze : {}", e.attributeValue("analyze"));
logger.debug("field must : {}", e.attributeValue("must"));
logger.debug("field boost : {}", e.attributeValue("boost"));
logger.debug("field termposition : {}", e.attributeValue("termposition"));
logger.debug("field termoffset : {}", e.attributeValue("termoffset"));
}
}
for(Element e : fieldsList) {
CollectionField collectionField = new CollectionField();
collectionField.setName(e.attributeValue("name"));
collectionField.setisStore(Boolean.valueOf(e.attributeValue("store")));
collectionField.setisIndexing(Boolean.valueOf(e.attributeValue("index")));
collectionField.setType(e.attributeValue("type"));
collectionField.setisAnalyze(Boolean.valueOf(e.attributeValue("analyze")));
collectionField.setisMust(Boolean.valueOf(e.attributeValue("must")));
collectionField.setFieldBoost(Float.parseFloat(StringUtils.defaultString(e.attributeValue("boost"), "0")));
collectionField.setHasTermOffset(Boolean.valueOf(e.attributeValue("termoffset")));
collectionField.setHasTermPosition(Boolean.valueOf(e.attributeValue("termposition")));
collectionField.setHasTermVector(Boolean.valueOf(e.attributeValue("termvector")));
collection.putField(collectionField.getName(), collectionField);
collection.addFieldName(collectionField.getName());
}
@SuppressWarnings("unchecked")
List<Element> defaultSearchFields = node.selectNodes("//defaultSearchField");
if(logger.isDebugEnabled()) {
for(Element e : defaultSearchFields) {
logger.debug("default search fields : {}", e.attributeValue("name"));
}
}
for(Element e : defaultSearchFields) {
collection.addDefaultSearchFieldNames(e.attributeValue("name"));
}
@SuppressWarnings("unchecked")
List<Element> sortFields = node.selectNodes("//sortField");
if(logger.isDebugEnabled()) {
for(Element e : sortFields) {
logger.debug("sortField source : {}", e.attributeValue("source"));
logger.debug("sortField dest : {}", e.attributeValue("dest"));
}
}
for(Element e : sortFields) {
String srcFieldName = e.attributeValue("source");
CollectionField srcField = collection.getFieldsByName().get(srcFieldName);
if(srcField == null) {
throw new IllegalStateException("정렬 필드 설정에 필요한 원본(source) 필드가 없습니다.");
}
try {
String dstFieldName = e.attributeValue("dest");
CollectionField dstField = (CollectionField) srcField.clone();
dstField.setisAnalyze(false);
dstField.setisIndexing(true);
dstField.setName(dstFieldName);
collection.putField(dstFieldName, dstField);
collection.addSortFieldNames(dstFieldName);
} catch (CloneNotSupportedException e1) {
logger.error("error : ", e1);
}
}
collections.put(collection.getCollectionName(), collection);
}// end for(Element node : collectionList)
logger.debug("collections : {}", collections);
}
| private void initProperty() {
ResourceLoader resourceLoader = new ResourceLoader(DEFAULT_CONFIG_XML);
Document document = resourceLoader.getDocument();
//get collection list
@SuppressWarnings("unchecked")
List<Element> collectionList = document.selectNodes("//collection");
logger.debug("collectionList : {}", collectionList.toString());
for(Element node : collectionList) {
Collection collection = new Collection();
logger.debug("indexingDirectory : {}", node.elementText("indexingDirectory"));
logger.debug("name : {}", node.attributeValue("name"));
collection.setIndexingDir(node.elementText("indexingDirectory"));
collection.setCollectionName(node.attributeValue("name"));
@SuppressWarnings("unchecked")
List<Element> fieldsList = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"/fields/field");
if(logger.isDebugEnabled()) {
for(Element e : fieldsList) {
logger.debug("field name : {}", e.attributeValue("name"));
logger.debug("field store : {}", e.attributeValue("store"));
logger.debug("field index : {}", e.attributeValue("index"));
logger.debug("field type : {}", e.attributeValue("type"));
logger.debug("field analyze : {}", e.attributeValue("analyze"));
logger.debug("field must : {}", e.attributeValue("must"));
logger.debug("field boost : {}", e.attributeValue("boost"));
logger.debug("field termposition : {}", e.attributeValue("termposition"));
logger.debug("field termoffset : {}", e.attributeValue("termoffset"));
}
}
for(Element e : fieldsList) {
CollectionField collectionField = new CollectionField();
collectionField.setName(e.attributeValue("name"));
collectionField.setisStore(Boolean.valueOf(e.attributeValue("store")));
collectionField.setisIndexing(Boolean.valueOf(e.attributeValue("index")));
collectionField.setType(e.attributeValue("type"));
collectionField.setisAnalyze(Boolean.valueOf(e.attributeValue("analyze")));
collectionField.setisMust(Boolean.valueOf(e.attributeValue("must")));
collectionField.setFieldBoost(Float.parseFloat(StringUtils.defaultString(e.attributeValue("boost"), "0")));
collectionField.setHasTermOffset(Boolean.valueOf(e.attributeValue("termoffset")));
collectionField.setHasTermPosition(Boolean.valueOf(e.attributeValue("termposition")));
collectionField.setHasTermVector(Boolean.valueOf(e.attributeValue("termvector")));
collection.putField(collectionField.getName(), collectionField);
collection.addFieldName(collectionField.getName());
}
@SuppressWarnings("unchecked")
List<Element> defaultSearchFields = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"//defaultSearchFields/defaultSearchField");
if(logger.isDebugEnabled()) {
for(Element e : defaultSearchFields) {
logger.debug("default search fields : {}", e.attributeValue("name"));
}
}
for(Element e : defaultSearchFields) {
collection.addDefaultSearchFieldNames(e.attributeValue("name"));
}
@SuppressWarnings("unchecked")
List<Element> sortFields = node.selectNodes("//collection[@name='"+collection.getCollectionName()+"']"+"//sortFields/sortField");
if(logger.isDebugEnabled()) {
for(Element e : sortFields) {
logger.debug("sortField source : {}", e.attributeValue("source"));
logger.debug("sortField dest : {}", e.attributeValue("dest"));
}
}
for(Element e : sortFields) {
String srcFieldName = e.attributeValue("source");
CollectionField srcField = collection.getFieldsByName().get(srcFieldName);
if(srcField == null) {
throw new IllegalStateException("정렬 필드 설정에 필요한 원본(source) 필드가 없습니다.");
}
try {
String dstFieldName = e.attributeValue("dest");
CollectionField dstField = (CollectionField) srcField.clone();
dstField.setisAnalyze(false);
dstField.setisIndexing(true);
dstField.setName(dstFieldName);
collection.putField(dstFieldName, dstField);
collection.addSortFieldNames(dstFieldName);
} catch (CloneNotSupportedException e1) {
logger.error("error : ", e1);
}
}
collections.put(collection.getCollectionName(), collection);
}// end for(Element node : collectionList)
logger.debug("collections : {}", collections);
}
|
diff --git a/src/main/java/com/ribomation/droidAtScreen/gui/DeviceFrame.java b/src/main/java/com/ribomation/droidAtScreen/gui/DeviceFrame.java
index 087d9d7..aaa73c0 100644
--- a/src/main/java/com/ribomation/droidAtScreen/gui/DeviceFrame.java
+++ b/src/main/java/com/ribomation/droidAtScreen/gui/DeviceFrame.java
@@ -1,355 +1,355 @@
package com.ribomation.droidAtScreen.gui;
import com.ribomation.droidAtScreen.Application;
import com.ribomation.droidAtScreen.Settings;
import com.ribomation.droidAtScreen.cmd.*;
import com.ribomation.droidAtScreen.dev.AndroidDevice;
import com.ribomation.droidAtScreen.dev.ScreenImage;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.TimerTask;
/**
* Frame holder for the device image.
*/
public class DeviceFrame extends JFrame implements Comparable<DeviceFrame> {
private final static RenderingHints HINTS = new RenderingHints(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
private final Application app;
private final AndroidDevice device;
private Logger log;
private int scalePercentage = 100;
private boolean landscapeMode = false;
private boolean upsideDown = false;
private ImageCanvas canvas;
private JComponent toolBar;
private RecordingListener recordingListener;
private TimerTask retriever;
private InfoPane infoPane;
public DeviceFrame(Application app, AndroidDevice device) {
this.app = app;
this.device = device;
this.log = Logger.getLogger(DeviceFrame.class.getName() + ":" +
device.getName());
log.debug(String.format("DeviceFrame(device=%s)", device));
Settings cfg = app.getSettings();
setScale(cfg.getPreferredScale());
setLandscapeMode(cfg.isLandscape());
setTitle(device.getName());
setIconImage(GuiUtil.loadIcon("device").getImage());
setResizable(false);
add(canvas = new ImageCanvas(), BorderLayout.CENTER);
add(toolBar = createToolBar(), BorderLayout.WEST);
add(infoPane = new InfoPane(), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- addWindowStateListener(new WindowAdapter() {
+ addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
log.debug("windowClosing");
stopRetriever();
DeviceFrame.this.setVisible(false);
DeviceFrame.this.app.getDeviceTableModel().refresh();
}
});
startRetriever();
pack();
}
public void startRetriever() {
retriever = new Retriever();
app.getTimer().schedule(retriever, 0, 500);
}
public void stopRetriever() {
retriever.cancel();
}
class Retriever extends TimerTask {
@Override
public void run() {
long start = System.currentTimeMillis();
ScreenImage image = device.getScreenImage();
long elapsed = System.currentTimeMillis() - start;
infoPane.setElapsed(elapsed, image);
infoPane.setStatus(device.getState().name().toUpperCase());
log.debug(String.format("Got screenshot %s, elapsed %d ms", image,
elapsed));
boolean fresh = canvas.getScreenshot() == null;
if (image != null) {
if (recordingListener != null) recordingListener.record(image);
canvas.setScreenshot(image);
infoPane.setSizeInfo(canvas);
}
if (fresh) {
log = Logger.getLogger(DeviceFrame.class.getName() + ":" +
device.getName());
setTitle(device.getName());
pack();
app.getDeviceTableModel().refresh();
}
}
}
protected JComponent createToolBar() {
JPanel buttons = new JPanel(new GridLayout(6, 1, 0, 8));
buttons.add(new OrientationCommand(this).newButton());
buttons.add(new UpsideDownCommand(this).newButton());
buttons.add(new ScaleCommand(this).newButton());
buttons.add(new ScreenshotCommand(this).newButton());
buttons.add(new RecordingCommand(this).newButton());
buttons.add(new PropertiesCommand(this).newButton());
JPanel tb = new JPanel(new FlowLayout());
tb.setBorder(BorderFactory.createEmptyBorder());
tb.add(buttons);
return tb;
}
public class InfoPane extends JPanel {
JLabel size, status, elapsed;
InfoPane() {
super(new GridLayout(1, 2, 3, 0));
setBorder(BorderFactory.createEmptyBorder());
Font font = getFont().deriveFont(Font.PLAIN, 12.0F);
status = new JLabel("UNKNOWN");
status.setFont(font);
status.setHorizontalAlignment(SwingConstants.LEADING);
status.setToolTipText("Device status");
size = new JLabel("? x ?");
size.setFont(font);
size.setHorizontalAlignment(SwingConstants.CENTER);
size.setToolTipText("Image dimension and size");
elapsed = new JLabel("");
elapsed.setFont(font);
elapsed.setHorizontalAlignment(SwingConstants.RIGHT);
elapsed.setToolTipText("Elapsed time and rate of last screenshot");
this.add(status);
this.add(size);
this.add(elapsed);
}
void setSizeInfo(ImageCanvas img) {
Dimension sz = img.getPreferredSize();
size.setText(String.format("%dx%d (%s)", sz.width, sz.height,
new Unit(img.getScreenshot().getRawImage().size).toString()));
}
public void setStatus(String devStatus) {
status.setText(devStatus);
}
public void setElapsed(long time, ScreenImage img) {
int sz = (img != null ? (int)(img.getRawImage().size / (time / 1000.0)) :
0);
elapsed.setText(String.format("%d ms (%s/s)", time,
new Unit(sz).toString()));
}
}
class Unit {
final int K = 1024;
final int M = K * K;
final int G = K * M;
long value;
Unit(long value) {
this.value = value;
}
String unit() {
if (value / G > 0) return "Gb";
if (value / M > 0) return "Mb";
if (value / K > 0) return "Kb";
return "bytes";
}
float value() {
if (value / G > 0) return (float)value / G;
if (value / M > 0) return (float)value / M;
if (value / K > 0) return (float)value / K;
return value;
}
public String toString() {
return String.format("%.1f %s", value(), unit());
}
}
class ImageCanvas extends JComponent {
private ScreenImage image;
public ImageCanvas() {
setBorder(BorderFactory.createLoweredBevelBorder());
}
public void setScreenshot(ScreenImage image) {
this.image = image;
repaint();
}
public ScreenImage getScreenshot() {
return image;
}
@Override
protected void paintComponent(Graphics g) {
if (image != null && g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D)g;
AffineTransform TX = new AffineTransform();
BufferedImage bufImg = image.toBufferedImage();
if (landscapeMode) {
bufImg = toLandscape(bufImg);
}
if (scalePercentage != 100) {
double scale = scalePercentage / 100.0;
TX.concatenate(AffineTransform.getScaleInstance(scale, scale));
}
if (upsideDown) {
int w = image.getWidth();
int h = image.getHeight();
double x = (landscapeMode ? h : w) / 2;
double y = (landscapeMode ? w : h) / 2;
TX.concatenate(AffineTransform.getQuadrantRotateInstance(2, x, y));
}
g2.drawImage(bufImg, TX, null);
} else {
g.setColor(Color.RED);
g.setFont(getFont().deriveFont(16.0F));
g.drawString("No screenshot yet", 10, 25);
}
}
BufferedImage toLandscape(BufferedImage img) {
return rotate(3, img);
}
BufferedImage rotate(int quadrants, BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
int x = (quadrants == 2 || quadrants == 3) ? w : 0;
int y = (quadrants == 1 || quadrants == 2) ? h : 0;
Point2D origo = AffineTransform.getQuadrantRotateInstance(quadrants, 0, 0)
.transform(new Point(x, y), null);
BufferedImage result = new BufferedImage(h, w, img.getType());
Graphics2D g = result.createGraphics();
g.translate(0 - origo.getX(), 0 - origo.getY());
g.transform(AffineTransform.getQuadrantRotateInstance(quadrants, 0, 0));
g.drawRenderedImage(img, null);
return result;
}
@Override
public Dimension getPreferredSize() {
if (image == null) return new Dimension(200, 300);
if (landscapeMode) {
return new Dimension(scale(image.getHeight()), scale(image.getWidth()));
}
return new Dimension(scale(image.getWidth()), scale(image.getHeight()));
}
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
}
public void setLandscapeMode(boolean landscape) {
this.landscapeMode = landscape;
}
public void setScale(int scalePercentage) {
this.scalePercentage = scalePercentage;
}
public void setUpsideDown(boolean upsideDown) {
this.upsideDown = upsideDown;
}
public void setRecordingListener(RecordingListener recordingListener) {
this.recordingListener = recordingListener;
}
public ScreenImage getLastScreenshot() {
return canvas.getScreenshot();
}
public InfoPane getInfoPane() {
return infoPane;
}
public AndroidDevice getDevice() {
return device;
}
public String getName() {
return device.getName();
}
public boolean isLandscapeMode() {
return landscapeMode;
}
public int getScale() {
return scalePercentage;
}
public boolean isUpsideDown() {
return upsideDown;
}
private int scale(int value) {
if (scalePercentage == 100) return value;
return (int)Math.round(value * scalePercentage / 100.0);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeviceFrame that = (DeviceFrame)o;
return this.device.getName().equals(that.device.getName());
}
@Override
public int hashCode() {
return device.getName().hashCode();
}
@Override
public int compareTo(DeviceFrame that) {
return this.getName().compareTo(that.getName());
}
}
| true | true | public DeviceFrame(Application app, AndroidDevice device) {
this.app = app;
this.device = device;
this.log = Logger.getLogger(DeviceFrame.class.getName() + ":" +
device.getName());
log.debug(String.format("DeviceFrame(device=%s)", device));
Settings cfg = app.getSettings();
setScale(cfg.getPreferredScale());
setLandscapeMode(cfg.isLandscape());
setTitle(device.getName());
setIconImage(GuiUtil.loadIcon("device").getImage());
setResizable(false);
add(canvas = new ImageCanvas(), BorderLayout.CENTER);
add(toolBar = createToolBar(), BorderLayout.WEST);
add(infoPane = new InfoPane(), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowStateListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
log.debug("windowClosing");
stopRetriever();
DeviceFrame.this.setVisible(false);
DeviceFrame.this.app.getDeviceTableModel().refresh();
}
});
startRetriever();
pack();
}
| public DeviceFrame(Application app, AndroidDevice device) {
this.app = app;
this.device = device;
this.log = Logger.getLogger(DeviceFrame.class.getName() + ":" +
device.getName());
log.debug(String.format("DeviceFrame(device=%s)", device));
Settings cfg = app.getSettings();
setScale(cfg.getPreferredScale());
setLandscapeMode(cfg.isLandscape());
setTitle(device.getName());
setIconImage(GuiUtil.loadIcon("device").getImage());
setResizable(false);
add(canvas = new ImageCanvas(), BorderLayout.CENTER);
add(toolBar = createToolBar(), BorderLayout.WEST);
add(infoPane = new InfoPane(), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
log.debug("windowClosing");
stopRetriever();
DeviceFrame.this.setVisible(false);
DeviceFrame.this.app.getDeviceTableModel().refresh();
}
});
startRetriever();
pack();
}
|
diff --git a/java/modules/transports/optional/amqp/src/test/java/org/apache/synapse/tranport/amqp/AMQPConsumerClient.java b/java/modules/transports/optional/amqp/src/test/java/org/apache/synapse/tranport/amqp/AMQPConsumerClient.java
index c100f2330..0d35f3829 100644
--- a/java/modules/transports/optional/amqp/src/test/java/org/apache/synapse/tranport/amqp/AMQPConsumerClient.java
+++ b/java/modules/transports/optional/amqp/src/test/java/org/apache/synapse/tranport/amqp/AMQPConsumerClient.java
@@ -1,34 +1,36 @@
package org.apache.synapse.tranport.amqp;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.io.IOException;
/**
* The consumer client for AMQP transport
*/
public class AMQPConsumerClient {
public static final String QUEUE_NAME = "ProducerProxy";
public static void main(String[] args) throws IOException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
System.out.println("Waiting for message on queue '" + QUEUE_NAME + "'");
- QueueingConsumer.Delivery delivery = consumer.nextDelivery();
- String message = new String(delivery.getBody());
- System.out.println("[x] received '" + message + "'");
+ while (true) {
+ QueueingConsumer.Delivery delivery = consumer.nextDelivery();
+ String message = new String(delivery.getBody());
+ System.out.println("[x] received '" + message + "'");
+ }
}
}
| true | true | public static void main(String[] args) throws IOException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
System.out.println("Waiting for message on queue '" + QUEUE_NAME + "'");
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("[x] received '" + message + "'");
}
| public static void main(String[] args) throws IOException, InterruptedException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);
System.out.println("Waiting for message on queue '" + QUEUE_NAME + "'");
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println("[x] received '" + message + "'");
}
}
|
diff --git a/library/src/com/haarman/listviewanimations/itemmanipulation/ExpandableListItemAdapter.java b/library/src/com/haarman/listviewanimations/itemmanipulation/ExpandableListItemAdapter.java
index 1a8f81b..a1955d1 100644
--- a/library/src/com/haarman/listviewanimations/itemmanipulation/ExpandableListItemAdapter.java
+++ b/library/src/com/haarman/listviewanimations/itemmanipulation/ExpandableListItemAdapter.java
@@ -1,292 +1,292 @@
package com.haarman.listviewanimations.itemmanipulation;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.haarman.listviewanimations.ArrayAdapter;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
/**
* An {@link ArrayAdapter} which allows items to be expanded using an animation.
*/
public abstract class ExpandableListItemAdapter<T> extends ArrayAdapter<T> {
private static final int DEFAULTTITLEPARENTRESID = 10000;
private static final int DEFAULTCONTENTPARENTRESID = 10001;
private Context mContext;
private int mViewLayoutResId;
private int mTitleParentResId;
private int mContentParentResId;
private int mActionViewResId;
private List<Long> mVisibleIds;
/**
* Creates a new ExpandableListItemAdapter with an empty list.
*/
protected ExpandableListItemAdapter(Context context) {
this(context, null);
}
/**
* Creates a new {@link ExpandableListItemAdapter} with the specified list,
* or an empty list if items == null.
*/
protected ExpandableListItemAdapter(Context context, List<T> items) {
super(items);
mContext = context;
mTitleParentResId = DEFAULTTITLEPARENTRESID;
mContentParentResId = DEFAULTCONTENTPARENTRESID;
mVisibleIds = new ArrayList<Long>();
}
/**
* Creates a new ExpandableListItemAdapter with an empty list. Uses given
* layout resource for the view; titleParentResId and contentParentResId
* should be identifiers for ViewGroups within that layout.
*/
protected ExpandableListItemAdapter(Context context, int layoutResId, int titleParentResId, int contentParentResId) {
this(context, layoutResId, titleParentResId, contentParentResId, null);
}
/**
* Creates a new ExpandableListItemAdapter with the specified list, or an
* empty list if items == null. Uses given layout resource for the view;
* titleParentResId and contentParentResId should be identifiers for
* ViewGroups within that layout.
*/
protected ExpandableListItemAdapter(Context context, int layoutResId, int titleParentResId, int contentParentResId, List<T> items) {
super(items);
mContext = context;
mViewLayoutResId = layoutResId;
mTitleParentResId = titleParentResId;
mContentParentResId = contentParentResId;
mVisibleIds = new ArrayList<Long>();
}
/**
* Set the resource id of the child {@link View} contained in the View returned by
* {@link #getTitleView(int, View, ViewGroup)} that will be the actuator of the expand / collapse animations.<br>
* If there is no View in the title View with given resId, a {@link NullPointerException} is thrown.</p>
* Default behavior: the whole title View acts as the actuator.
* @param resId the resource id.
*/
public void setActionViewResId(int resId) {
mActionViewResId = resId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup view = (ViewGroup) convertView;
ViewHolder viewHolder;
if (view == null) {
view = createView(parent);
viewHolder = new ViewHolder();
viewHolder.titleParent = (ViewGroup) view.findViewById(mTitleParentResId);
viewHolder.contentParent = (ViewGroup) view.findViewById(mContentParentResId);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
View titleView = getTitleView(position, viewHolder.titleView, viewHolder.titleParent);
- if (!titleView.equals(viewHolder.titleView)) {
+ if (titleView != viewHolder.titleView) {
viewHolder.titleParent.removeAllViews();
viewHolder.titleParent.addView(titleView);
if (mActionViewResId == 0) {
view.setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
} else {
view.findViewById(mActionViewResId).setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
}
}
viewHolder.titleView = titleView;
View contentView = getContentView(position, viewHolder.contentView, viewHolder.contentParent);
- if (!contentView.equals(viewHolder.contentView)) {
+ if (contentView != viewHolder.contentView) {
viewHolder.contentParent.removeAllViews();
viewHolder.contentParent.addView(contentView);
}
- viewHolder.titleView = titleView;
+ viewHolder.contentParent = contentParent;
viewHolder.contentParent.setVisibility(mVisibleIds.contains(getItemId(position)) ? View.VISIBLE : View.GONE);
viewHolder.contentParent.setTag(getItemId(position));
return view;
}
private ViewGroup createView(ViewGroup parent) {
ViewGroup view;
if (mViewLayoutResId == 0) {
view = new RootView(mContext);
} else {
view = (ViewGroup) LayoutInflater.from(mContext).inflate(mViewLayoutResId, parent, false);
}
return view;
}
/**
* Get a View that displays the title of the data at the specified position
* in the data set. You can either create a View manually or inflate it from
* an XML layout file. When the View is inflated, the parent View (GridView,
* ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position
* The position of the item within the adapter's data set of the
* item whose view we want.
* @param convertView
* The old view to reuse, if possible. Note: You should check
* that this view is non-null and of an appropriate type before
* using. If it is not possible to convert this view to display
* the correct data, this method can create a new view.
* @param parent
* The parent that this view will eventually be attached to
* @return A View corresponding to the title of the data at the specified
* position.
*/
public abstract View getTitleView(int position, View convertView, ViewGroup parent);
/**
* Get a View that displays the content of the data at the specified
* position in the data set. You can either create a View manually or
* inflate it from an XML layout file. When the View is inflated, the parent
* View (GridView, ListView...) will apply default layout parameters unless
* you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position
* The position of the item within the adapter's data set of the
* item whose view we want.
* @param convertView
* The old view to reuse, if possible. Note: You should check
* that this view is non-null and of an appropriate type before
* using. If it is not possible to convert this view to display
* the correct data, this method can create a new view.
* @param parent
* The parent that this view will eventually be attached to
* @return A View corresponding to the content of the data at the specified
* position.
*/
public abstract View getContentView(int position, View convertView, ViewGroup parent);
private static class ViewHolder {
ViewGroup titleParent;
ViewGroup contentParent;
View titleView;
View contentView;
}
private static class RootView extends LinearLayout {
private ViewGroup mTitleViewGroup;
private ViewGroup mContentViewGroup;
public RootView(Context context) {
super(context);
init();
}
private void init() {
setOrientation(VERTICAL);
mTitleViewGroup = new FrameLayout(getContext());
mTitleViewGroup.setId(DEFAULTTITLEPARENTRESID);
addView(mTitleViewGroup);
mContentViewGroup = new FrameLayout(getContext());
mContentViewGroup.setId(DEFAULTCONTENTPARENTRESID);
addView(mContentViewGroup);
}
}
private class TitleViewOnClickListener implements View.OnClickListener {
private View mContentParent;
private TitleViewOnClickListener(View contentParent) {
this.mContentParent = contentParent;
}
@Override
public void onClick(View view) {
boolean isVisible = mContentParent.getVisibility() == View.VISIBLE;
if (isVisible) {
animateCollapsing();
mVisibleIds.remove(mContentParent.getTag());
} else {
animateExpanding();
mVisibleIds.add((Long) mContentParent.getTag());
}
}
private void animateCollapsing() {
int origHeight = mContentParent.getHeight();
ValueAnimator animator = createHeightAnimator(origHeight, 0);
animator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
mContentParent.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
animator.start();
}
private void animateExpanding() {
mContentParent.setVisibility(View.VISIBLE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
mContentParent.measure(widthSpec, heightSpec);
ValueAnimator animator = createHeightAnimator(0, mContentParent.getMeasuredHeight());
animator.start();
}
private ValueAnimator createHeightAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mContentParent.getLayoutParams();
layoutParams.height = value;
mContentParent.setLayoutParams(layoutParams);
}
});
return animator;
}
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup view = (ViewGroup) convertView;
ViewHolder viewHolder;
if (view == null) {
view = createView(parent);
viewHolder = new ViewHolder();
viewHolder.titleParent = (ViewGroup) view.findViewById(mTitleParentResId);
viewHolder.contentParent = (ViewGroup) view.findViewById(mContentParentResId);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
View titleView = getTitleView(position, viewHolder.titleView, viewHolder.titleParent);
if (!titleView.equals(viewHolder.titleView)) {
viewHolder.titleParent.removeAllViews();
viewHolder.titleParent.addView(titleView);
if (mActionViewResId == 0) {
view.setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
} else {
view.findViewById(mActionViewResId).setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
}
}
viewHolder.titleView = titleView;
View contentView = getContentView(position, viewHolder.contentView, viewHolder.contentParent);
if (!contentView.equals(viewHolder.contentView)) {
viewHolder.contentParent.removeAllViews();
viewHolder.contentParent.addView(contentView);
}
viewHolder.titleView = titleView;
viewHolder.contentParent.setVisibility(mVisibleIds.contains(getItemId(position)) ? View.VISIBLE : View.GONE);
viewHolder.contentParent.setTag(getItemId(position));
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup view = (ViewGroup) convertView;
ViewHolder viewHolder;
if (view == null) {
view = createView(parent);
viewHolder = new ViewHolder();
viewHolder.titleParent = (ViewGroup) view.findViewById(mTitleParentResId);
viewHolder.contentParent = (ViewGroup) view.findViewById(mContentParentResId);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
View titleView = getTitleView(position, viewHolder.titleView, viewHolder.titleParent);
if (titleView != viewHolder.titleView) {
viewHolder.titleParent.removeAllViews();
viewHolder.titleParent.addView(titleView);
if (mActionViewResId == 0) {
view.setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
} else {
view.findViewById(mActionViewResId).setOnClickListener(new TitleViewOnClickListener(viewHolder.contentParent));
}
}
viewHolder.titleView = titleView;
View contentView = getContentView(position, viewHolder.contentView, viewHolder.contentParent);
if (contentView != viewHolder.contentView) {
viewHolder.contentParent.removeAllViews();
viewHolder.contentParent.addView(contentView);
}
viewHolder.contentParent = contentParent;
viewHolder.contentParent.setVisibility(mVisibleIds.contains(getItemId(position)) ? View.VISIBLE : View.GONE);
viewHolder.contentParent.setTag(getItemId(position));
return view;
}
|
diff --git a/src/com/dmdirc/ui/swing/dialogs/actionsmanager/ActionGroupSettingsPanel.java b/src/com/dmdirc/ui/swing/dialogs/actionsmanager/ActionGroupSettingsPanel.java
index 8a15bc9c2..65a9b699c 100644
--- a/src/com/dmdirc/ui/swing/dialogs/actionsmanager/ActionGroupSettingsPanel.java
+++ b/src/com/dmdirc/ui/swing/dialogs/actionsmanager/ActionGroupSettingsPanel.java
@@ -1,180 +1,180 @@
/*
* Copyright (c) 2006-2008 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.ui.swing.dialogs.actionsmanager;
import com.dmdirc.actions.ActionGroup;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.ui.swing.PrefsComponentFactory;
import com.dmdirc.ui.swing.components.ColourChooser;
import com.dmdirc.ui.swing.components.OptionalColourChooser;
import com.dmdirc.ui.swing.components.durationeditor.DurationDisplay;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
/**
* Action group settings panel.
*/
public final class ActionGroupSettingsPanel extends JPanel implements ActionListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** Settings list. */
private Collection<PreferencesSetting> settings;
/** Button -> Component map. */
private Map<JButton, PreferencesSetting> settingMap;
/** Parent dialog. */
private Window window;
/**
* Initialises a new action group information panel.
*
* @param group Action group
*/
public ActionGroupSettingsPanel(final ActionGroup group) {
this(group, null);
}
/**
* Initialises a new action group information panel.
*
* @param group Action group
* @param window Parent window
*
* @since 0.6
*/
public ActionGroupSettingsPanel(final ActionGroup group, final Window window) {
super();
this.window = window;
initComponents();
addListeners();
setActionGroup(group);
}
/**
* Initialises the components.
*/
private void initComponents() {
settingMap = new HashMap<JButton, PreferencesSetting>();
}
/**
* Adds listeners.
*/
private void addListeners() {
//Empty
}
/**
* Lays out the components.
*/
private void layoutComponents() {
removeAll();
- setLayout(new MigLayout("fill, wrap 2, hidemode 3"));
+ setLayout(new MigLayout("fill, hidemode 3"));
for (PreferencesSetting setting : settings) {
final JLabel label = new JLabel(setting.getTitle());
label.setToolTipText(setting.getTitle());
final JComponent component =
PrefsComponentFactory.getComponent(setting);
if (component instanceof DurationDisplay) {
((DurationDisplay) component).setWindow(window);
} else if (component instanceof ColourChooser) {
((ColourChooser) component).setWindow(window);
} else if (component instanceof OptionalColourChooser) {
((OptionalColourChooser) component).setWindow(window);
}
final JButton button = new SettingsRevertButton(setting);
settingMap.put(button, setting);
button.addActionListener(this);
- add(label, "");
- add(component, "split 2, span, growx");
- add(button, "wrap");
+ add(label, "newline");
+ add(component, "growx");
+ add(button, "");
}
}
/**
* Sets the action group for the panel.
*
* @param group New action group
*/
public void setActionGroup(final ActionGroup group) {
if (group == null || group.getSettings().isEmpty()) {
this.settings = new ArrayList<PreferencesSetting>();
} else {
this.settings = group.getSettings().values();
}
layoutComponents();
}
/**
* Should the settings panel be shown?
*
* @return true iif the panel should be shown
*/
public boolean shouldDisplay() {
return !settings.isEmpty();
}
/**
* Saves the changes to the settings.
*/
public void save() {
for (PreferencesSetting setting : settings) {
setting.save();
}
}
/**
* {@inheritDoc}
*
* @param e Action event
*/
@Override
public void actionPerformed(final ActionEvent e) {
setVisible(false);
settingMap.get(e.getSource()).dismiss();
layoutComponents();
setVisible(true);
}
}
| false | true | private void layoutComponents() {
removeAll();
setLayout(new MigLayout("fill, wrap 2, hidemode 3"));
for (PreferencesSetting setting : settings) {
final JLabel label = new JLabel(setting.getTitle());
label.setToolTipText(setting.getTitle());
final JComponent component =
PrefsComponentFactory.getComponent(setting);
if (component instanceof DurationDisplay) {
((DurationDisplay) component).setWindow(window);
} else if (component instanceof ColourChooser) {
((ColourChooser) component).setWindow(window);
} else if (component instanceof OptionalColourChooser) {
((OptionalColourChooser) component).setWindow(window);
}
final JButton button = new SettingsRevertButton(setting);
settingMap.put(button, setting);
button.addActionListener(this);
add(label, "");
add(component, "split 2, span, growx");
add(button, "wrap");
}
}
| private void layoutComponents() {
removeAll();
setLayout(new MigLayout("fill, hidemode 3"));
for (PreferencesSetting setting : settings) {
final JLabel label = new JLabel(setting.getTitle());
label.setToolTipText(setting.getTitle());
final JComponent component =
PrefsComponentFactory.getComponent(setting);
if (component instanceof DurationDisplay) {
((DurationDisplay) component).setWindow(window);
} else if (component instanceof ColourChooser) {
((ColourChooser) component).setWindow(window);
} else if (component instanceof OptionalColourChooser) {
((OptionalColourChooser) component).setWindow(window);
}
final JButton button = new SettingsRevertButton(setting);
settingMap.put(button, setting);
button.addActionListener(this);
add(label, "newline");
add(component, "growx");
add(button, "");
}
}
|
diff --git a/src/TestBlock/mod_TestBlock.java b/src/TestBlock/mod_TestBlock.java
index a50c6f7..493198a 100644
--- a/src/TestBlock/mod_TestBlock.java
+++ b/src/TestBlock/mod_TestBlock.java
@@ -1,37 +1,37 @@
package net.minecraft.src;
import java.util.*;
public class mod_TestBlock extends BaseMod
{
public static Block TestBlock = new TestBlock(255, 0).setHardness(1.0f).setResistance(6000.0F).setLightValue(1.0F).setBlockName("TestBlock");
public String Version()
{
return "1.0";
}
public mod_TestBlock()
{
ModLoader.RegisterBlock(TestBlock);
TestBlock.blockIndexInTexture = ModLoader.addOverride("/terrain.png", "/bph.png");
ModLoader.AddName(TestBlock, "TestBlock");
ModLoader.AddRecipe(new ItemStack(TestBlock, 1), new Object[] {
"###", "###", "###", Character.valueOf('#'), Item.redstone
});
}
public void GenerateSurface(World world, Random rand, int chunkX, int chunkZ)
{
- for(int i = 0; i < 20; i++)
+ for(int i = 0; i < 10; i++)
{
int randPosX = chunkX + rand.nextInt(16);
- int randPosY = rand.nextInt(20);
+ int randPosY = rand.nextInt(40);
int randPosZ = chunkZ + rand.nextInt(16);
(new WorldGenMinable(mod_TestBlock.TestBlock.blockID, 10)).generate(world, rand, randPosX, randPosY, randPosZ);
}
}
}
| false | true | public void GenerateSurface(World world, Random rand, int chunkX, int chunkZ)
{
for(int i = 0; i < 20; i++)
{
int randPosX = chunkX + rand.nextInt(16);
int randPosY = rand.nextInt(20);
int randPosZ = chunkZ + rand.nextInt(16);
(new WorldGenMinable(mod_TestBlock.TestBlock.blockID, 10)).generate(world, rand, randPosX, randPosY, randPosZ);
}
}
| public void GenerateSurface(World world, Random rand, int chunkX, int chunkZ)
{
for(int i = 0; i < 10; i++)
{
int randPosX = chunkX + rand.nextInt(16);
int randPosY = rand.nextInt(40);
int randPosZ = chunkZ + rand.nextInt(16);
(new WorldGenMinable(mod_TestBlock.TestBlock.blockID, 10)).generate(world, rand, randPosX, randPosY, randPosZ);
}
}
|
diff --git a/GUI/TERMESGUI.java b/GUI/TERMESGUI.java
index bacd45d..142faab 100644
--- a/GUI/TERMESGUI.java
+++ b/GUI/TERMESGUI.java
@@ -1,131 +1,130 @@
import java.awt.*;
import javax.swing.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
@SuppressWarnings("serial")
public class TERMESGUI extends JFrame
{
JPanel pane = new JPanel();
SpringLayout layout;
JLabel leftPicLabel;
ImageIcon leftIcon;
JLabel rightPicLabel;
ImageIcon rightIcon;
//the size of the video feeds
int frameHeight;
int frameWidth;
double scale = 0.7;
public TERMESGUI()
{
InitializeWindow();
//test label
JLabel label = new JLabel(TERMESConnector.test());
pane.add(label);
//setup input feed
TERMESConnector.start();
//initialize the left icon and label that will contain the original video
leftIcon = new ImageIcon();
leftPicLabel = new JLabel(leftIcon);
leftPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(leftPicLabel);
//initialize the right icon and label that will contain the thresholded video
rightIcon = new ImageIcon();
rightPicLabel = new JLabel(rightIcon);
rightPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(rightPicLabel);
setLayoutConstraints();
setVisible(true); // display this frame
//poll for the next frame as long as there is one
byte[] frame;
while((frame = TERMESConnector.getNextFrame()) != null)
{
- System.out.println(TERMESConnector.getKeypoints()[1]);
//get the next frame as an image
Image img = TERMESImageProcessing.convertByteArrayToImage(frame);
//scale the image if necessary
if (frameHeight == 0) //then frameWidth is also 0
{
frameHeight = (int) determineFrameHeight(img.getWidth(null), img.getHeight(null));
frameWidth = (int) determineFrameWidth(img.getWidth(null), img.getHeight(null));
}
img = img.getScaledInstance(frameWidth, frameHeight ,java.awt.Image.SCALE_SMOOTH );
leftIcon = new ImageIcon(img);
rightIcon = new ImageIcon(img);
leftPicLabel.setIcon(leftIcon);
rightPicLabel.setIcon(rightIcon);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void InitializeWindow()
{
setTitle("TERMES");
setBounds(100, 100, 1100, 700);
Container con = this.getContentPane();
con.add(pane);
layout = new SpringLayout();
setLayout(layout);
//see to that the camera is released when the window is closed
// (if this isn't done, the application will crash when it is closed)
this.addWindowListener( new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
TERMESConnector.releaseCamera();
System.exit(0);
}
} );
}
public void setLayoutConstraints()
{
layout.putConstraint(SpringLayout.WEST, leftPicLabel, 50 ,SpringLayout.WEST, pane);
layout.putConstraint(SpringLayout.NORTH, leftPicLabel, 50 ,SpringLayout.NORTH, pane);
layout.putConstraint(SpringLayout.WEST, rightPicLabel, 50 ,SpringLayout.EAST, leftPicLabel);
layout.putConstraint(SpringLayout.NORTH, rightPicLabel, 50 ,SpringLayout.NORTH, pane);
}
public double determineFrameHeight(double width, double height)
{
if(width/height == 16.0/9.0) // 16:9
return 360 * scale;
else // 4:3
return 480 * scale;
}
public double determineFrameWidth(double width, double height)
{
if(width/height == 16.0/9.0) // 16:9
return 640 * scale;
else // 4:3
return 640 * scale;
}
}
| true | true | public TERMESGUI()
{
InitializeWindow();
//test label
JLabel label = new JLabel(TERMESConnector.test());
pane.add(label);
//setup input feed
TERMESConnector.start();
//initialize the left icon and label that will contain the original video
leftIcon = new ImageIcon();
leftPicLabel = new JLabel(leftIcon);
leftPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(leftPicLabel);
//initialize the right icon and label that will contain the thresholded video
rightIcon = new ImageIcon();
rightPicLabel = new JLabel(rightIcon);
rightPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(rightPicLabel);
setLayoutConstraints();
setVisible(true); // display this frame
//poll for the next frame as long as there is one
byte[] frame;
while((frame = TERMESConnector.getNextFrame()) != null)
{
System.out.println(TERMESConnector.getKeypoints()[1]);
//get the next frame as an image
Image img = TERMESImageProcessing.convertByteArrayToImage(frame);
//scale the image if necessary
if (frameHeight == 0) //then frameWidth is also 0
{
frameHeight = (int) determineFrameHeight(img.getWidth(null), img.getHeight(null));
frameWidth = (int) determineFrameWidth(img.getWidth(null), img.getHeight(null));
}
img = img.getScaledInstance(frameWidth, frameHeight ,java.awt.Image.SCALE_SMOOTH );
leftIcon = new ImageIcon(img);
rightIcon = new ImageIcon(img);
leftPicLabel.setIcon(leftIcon);
rightPicLabel.setIcon(rightIcon);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| public TERMESGUI()
{
InitializeWindow();
//test label
JLabel label = new JLabel(TERMESConnector.test());
pane.add(label);
//setup input feed
TERMESConnector.start();
//initialize the left icon and label that will contain the original video
leftIcon = new ImageIcon();
leftPicLabel = new JLabel(leftIcon);
leftPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(leftPicLabel);
//initialize the right icon and label that will contain the thresholded video
rightIcon = new ImageIcon();
rightPicLabel = new JLabel(rightIcon);
rightPicLabel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
add(rightPicLabel);
setLayoutConstraints();
setVisible(true); // display this frame
//poll for the next frame as long as there is one
byte[] frame;
while((frame = TERMESConnector.getNextFrame()) != null)
{
//get the next frame as an image
Image img = TERMESImageProcessing.convertByteArrayToImage(frame);
//scale the image if necessary
if (frameHeight == 0) //then frameWidth is also 0
{
frameHeight = (int) determineFrameHeight(img.getWidth(null), img.getHeight(null));
frameWidth = (int) determineFrameWidth(img.getWidth(null), img.getHeight(null));
}
img = img.getScaledInstance(frameWidth, frameHeight ,java.awt.Image.SCALE_SMOOTH );
leftIcon = new ImageIcon(img);
rightIcon = new ImageIcon(img);
leftPicLabel.setIcon(leftIcon);
rightPicLabel.setIcon(rightIcon);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/src/main/java/ch/o2it/weblounge/test/harness/PagesEndpointTest.java b/src/main/java/ch/o2it/weblounge/test/harness/PagesEndpointTest.java
index 20fa487a0..e784bb267 100644
--- a/src/main/java/ch/o2it/weblounge/test/harness/PagesEndpointTest.java
+++ b/src/main/java/ch/o2it/weblounge/test/harness/PagesEndpointTest.java
@@ -1,196 +1,196 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2010 The Weblounge Team
* http://weblounge.o2it.ch
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.o2it.weblounge.test.harness;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import ch.o2it.weblounge.common.impl.url.UrlSupport;
import ch.o2it.weblounge.common.impl.util.xml.XPathHelper;
import ch.o2it.weblounge.test.util.TestSiteUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.StringWriter;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/**
* Integration test to test the content repository's <code>restful</code> page
* api.
*/
public class PagesEndpointTest extends IntegrationTestBase {
/** The logger */
private static final Logger logger = LoggerFactory.getLogger(PagesEndpointTest.class);
/**
* Creates a new instance of the content repository's page endpoint test.
*/
public PagesEndpointTest() {
super("Page Endpoint Test");
}
/**
* {@inheritDoc}
*
* @see ch.o2it.weblounge.test.harness.IntegrationTest#execute(java.lang.String)
*/
public void execute(String serverUrl) throws Exception {
logger.info("Preparing test of pages endpoint");
// Include the mountpoint
// TODO: Make this dynamic
// serverUrl = UrlSupport.concat(serverUrl, "weblounge");
String requestUrl = UrlSupport.concat(serverUrl, "system/weblounge/pages");
- String testPath = "/testpath/";
+ String testPath = "/" + System.currentTimeMillis() + "/";
// Prepare the request
HttpPost createPageRequest = new HttpPost(requestUrl);
String[][] params = new String[][] { { "path", testPath } };
logger.debug("Creating new page at {}", createPageRequest.getURI());
HttpClient httpClient = new DefaultHttpClient();
String pageId = null;
try {
HttpResponse response = TestSiteUtils.request(httpClient, createPageRequest, params);
assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
assertEquals(0, response.getEntity().getContentLength());
// Extract the id of the new page
assertNotNull(response.getHeaders("Location"));
String locationHeader = response.getHeaders("Location")[0].getValue();
assertTrue(locationHeader.startsWith(serverUrl));
pageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
- assertNotNull(pageId);
+ assertEquals("Identifier doesn't have correct length", 36, pageId.length());
logger.debug("Id of the new page is {}", pageId);
} finally {
httpClient.getConnectionManager().shutdown();
}
// Check if a page has been created
HttpGet getPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
Document pageXml = null;
String creator = null;
logger.info("Requesting page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
creator = XPathHelper.valueOf(pageXml, "/page/head/created/user");
} finally {
httpClient.getConnectionManager().shutdown();
}
// Update the page
HttpPut updatePageRequest = new HttpPut(UrlSupport.concat(requestUrl, pageId));
String updatedCreator = creator + " (updated)";
NodeList creatorElements = pageXml.getElementsByTagName("created");
creatorElements.item(0).getFirstChild().setTextContent(updatedCreator);
- params = new String[][] { { "page", serializeDoc(pageXml) } };
+ params = new String[][] { { "content", serializeDoc(pageXml) } };
httpClient = new DefaultHttpClient();
logger.info("Updating page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, params);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure the update was successful
HttpGet getUpdatedPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Requesting updated page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getUpdatedPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
assertEquals(updatedCreator, XPathHelper.valueOf(pageXml, "/page/head/created/user"));
} finally {
httpClient.getConnectionManager().shutdown();
}
// Delete the page
HttpDelete deletePageRequest = new HttpDelete(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Sending delete request to {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, deletePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure it's gone
logger.info("Sending requests to {}", requestUrl);
httpClient = new DefaultHttpClient();
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
}
/**
* Returns the serialized version of the given dom node.
*
* @param doc
* the xml document
* @return the serialized version
*/
private static String serializeDoc(Node doc) {
StringWriter outText = new StringWriter();
StreamResult sr = new StreamResult(outText);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = null;
try {
t = tf.newTransformer();
t.transform(new DOMSource(doc), sr);
} catch (Throwable th) {
throw new IllegalStateException("Unable to serialize dom", th);
}
return outText.toString();
}
}
| false | true | public void execute(String serverUrl) throws Exception {
logger.info("Preparing test of pages endpoint");
// Include the mountpoint
// TODO: Make this dynamic
// serverUrl = UrlSupport.concat(serverUrl, "weblounge");
String requestUrl = UrlSupport.concat(serverUrl, "system/weblounge/pages");
String testPath = "/testpath/";
// Prepare the request
HttpPost createPageRequest = new HttpPost(requestUrl);
String[][] params = new String[][] { { "path", testPath } };
logger.debug("Creating new page at {}", createPageRequest.getURI());
HttpClient httpClient = new DefaultHttpClient();
String pageId = null;
try {
HttpResponse response = TestSiteUtils.request(httpClient, createPageRequest, params);
assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
assertEquals(0, response.getEntity().getContentLength());
// Extract the id of the new page
assertNotNull(response.getHeaders("Location"));
String locationHeader = response.getHeaders("Location")[0].getValue();
assertTrue(locationHeader.startsWith(serverUrl));
pageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
assertNotNull(pageId);
logger.debug("Id of the new page is {}", pageId);
} finally {
httpClient.getConnectionManager().shutdown();
}
// Check if a page has been created
HttpGet getPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
Document pageXml = null;
String creator = null;
logger.info("Requesting page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
creator = XPathHelper.valueOf(pageXml, "/page/head/created/user");
} finally {
httpClient.getConnectionManager().shutdown();
}
// Update the page
HttpPut updatePageRequest = new HttpPut(UrlSupport.concat(requestUrl, pageId));
String updatedCreator = creator + " (updated)";
NodeList creatorElements = pageXml.getElementsByTagName("created");
creatorElements.item(0).getFirstChild().setTextContent(updatedCreator);
params = new String[][] { { "page", serializeDoc(pageXml) } };
httpClient = new DefaultHttpClient();
logger.info("Updating page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, params);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure the update was successful
HttpGet getUpdatedPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Requesting updated page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getUpdatedPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
assertEquals(updatedCreator, XPathHelper.valueOf(pageXml, "/page/head/created/user"));
} finally {
httpClient.getConnectionManager().shutdown();
}
// Delete the page
HttpDelete deletePageRequest = new HttpDelete(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Sending delete request to {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, deletePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure it's gone
logger.info("Sending requests to {}", requestUrl);
httpClient = new DefaultHttpClient();
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
}
| public void execute(String serverUrl) throws Exception {
logger.info("Preparing test of pages endpoint");
// Include the mountpoint
// TODO: Make this dynamic
// serverUrl = UrlSupport.concat(serverUrl, "weblounge");
String requestUrl = UrlSupport.concat(serverUrl, "system/weblounge/pages");
String testPath = "/" + System.currentTimeMillis() + "/";
// Prepare the request
HttpPost createPageRequest = new HttpPost(requestUrl);
String[][] params = new String[][] { { "path", testPath } };
logger.debug("Creating new page at {}", createPageRequest.getURI());
HttpClient httpClient = new DefaultHttpClient();
String pageId = null;
try {
HttpResponse response = TestSiteUtils.request(httpClient, createPageRequest, params);
assertEquals(HttpServletResponse.SC_CREATED, response.getStatusLine().getStatusCode());
assertEquals(0, response.getEntity().getContentLength());
// Extract the id of the new page
assertNotNull(response.getHeaders("Location"));
String locationHeader = response.getHeaders("Location")[0].getValue();
assertTrue(locationHeader.startsWith(serverUrl));
pageId = locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
assertEquals("Identifier doesn't have correct length", 36, pageId.length());
logger.debug("Id of the new page is {}", pageId);
} finally {
httpClient.getConnectionManager().shutdown();
}
// Check if a page has been created
HttpGet getPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
Document pageXml = null;
String creator = null;
logger.info("Requesting page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
creator = XPathHelper.valueOf(pageXml, "/page/head/created/user");
} finally {
httpClient.getConnectionManager().shutdown();
}
// Update the page
HttpPut updatePageRequest = new HttpPut(UrlSupport.concat(requestUrl, pageId));
String updatedCreator = creator + " (updated)";
NodeList creatorElements = pageXml.getElementsByTagName("created");
creatorElements.item(0).getFirstChild().setTextContent(updatedCreator);
params = new String[][] { { "content", serializeDoc(pageXml) } };
httpClient = new DefaultHttpClient();
logger.info("Updating page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, params);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure the update was successful
HttpGet getUpdatedPageRequest = new HttpGet(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Requesting updated page at {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, getUpdatedPageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
pageXml = TestSiteUtils.parseXMLResponse(response);
assertEquals(pageId, XPathHelper.valueOf(pageXml, "/page/@id"));
assertEquals(testPath, XPathHelper.valueOf(pageXml, "/page/@path"));
assertEquals(updatedCreator, XPathHelper.valueOf(pageXml, "/page/head/created/user"));
} finally {
httpClient.getConnectionManager().shutdown();
}
// Delete the page
HttpDelete deletePageRequest = new HttpDelete(UrlSupport.concat(requestUrl, pageId));
httpClient = new DefaultHttpClient();
logger.info("Sending delete request to {}", requestUrl);
try {
HttpResponse response = TestSiteUtils.request(httpClient, deletePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
// Make sure it's gone
logger.info("Sending requests to {}", requestUrl);
httpClient = new DefaultHttpClient();
try {
HttpResponse response = TestSiteUtils.request(httpClient, updatePageRequest, null);
Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
} finally {
httpClient.getConnectionManager().shutdown();
}
}
|
diff --git a/src/ise/gameoflife/groups/TestPoliticalGroup.java b/src/ise/gameoflife/groups/TestPoliticalGroup.java
index f3bec14..5906257 100644
--- a/src/ise/gameoflife/groups/TestPoliticalGroup.java
+++ b/src/ise/gameoflife/groups/TestPoliticalGroup.java
@@ -1,106 +1,109 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ise.gameoflife.groups;
import ise.gameoflife.inputs.LeaveNotification.Reasons;
import ise.gameoflife.models.Food;
import ise.gameoflife.models.GroupDataInitialiser;
import ise.gameoflife.models.HuntingTeam;
import ise.gameoflife.participants.AbstractGroupAgent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Aadil
*/
public class TestPoliticalGroup extends AbstractGroupAgent {
private static final long serialVersionUID = 1L;
@Deprecated
public TestPoliticalGroup() {
super();
}
public TestPoliticalGroup(GroupDataInitialiser dm) {
super(dm);
}
@Override
protected void onActivate() {
// Do nothing.
}
@Override
protected boolean respondToJoinRequest(String playerID) {
double heuristic;
//used for the socio-economic faction of heuristic
double vectorDistance;
double maxDistance = Math.sqrt(2);
double economic, social, esFaction;
//used for the trust faction of heuristic
double trustFaction, trustSum = 0;
int numKnownTrustValues = 0;
//Obtain how much trust there is between the memberss of the group and the agent
for (String trustor : this.getDataModel().getMemberList()) {
Double trustValue = this.getConn().getAgentById(trustor).getTrust(playerID);
if (trustValue != null) {
trustSum += trustValue;
numKnownTrustValues++;
}
}
+ if (numKnownTrustValues == 0) {
+ return true;//this agent, playerID, wants to make a group of only himself
+ }
trustFaction = trustSum / numKnownTrustValues;
economic = this.getConn().getAgentById(playerID).getEconomicBelief() - this.getDataModel().getCurrentEconomicPoisition();//change in X
//social = this.getConn().getAgentById(playerID).getSocialBelief() - this.getDataModel().getEstimatedSocialLocation();//change in Y
social = 0.5;
vectorDistance = Math.sqrt(Math.pow(economic, 2) + Math.pow(social, 2));
esFaction = 1 - (vectorDistance / maxDistance);
heuristic = 0.5*trustFaction + 0.5*esFaction;
if (heuristic > 0.5) {
return true;
}
else {
return false;
}
}
/**
* Determines the optimum hunting choice in terms of the food gained/hunters needed ratio
* divides the group up into teams of this size, then passes them the order to hunt that food.
* If the group number doesn't divide easily, the excess will be put into a smaller team.
* This team will still be given the same order.
* @return the assignment of teams and which food they are to hunt.
*/
@Override
public List<HuntingTeam> selectTeams() {
ArrayList<HuntingTeam> teams = new ArrayList <HuntingTeam>();
List<String> members = getDataModel().getMemberList();
int agents = members.size();
for(int i=0; i < agents; i += 2){
int ubound = (i + 2 >= agents) ? agents : i + 2;
teams.add(new HuntingTeam(members.subList(i, ubound)));
}
return teams;
}
@Override
protected void onMemberLeave(String playerID, Reasons reason) {
// Do nothing
}
@Override
protected void beforeNewRound() {
// Do nothing
}
}
| true | true | protected boolean respondToJoinRequest(String playerID) {
double heuristic;
//used for the socio-economic faction of heuristic
double vectorDistance;
double maxDistance = Math.sqrt(2);
double economic, social, esFaction;
//used for the trust faction of heuristic
double trustFaction, trustSum = 0;
int numKnownTrustValues = 0;
//Obtain how much trust there is between the memberss of the group and the agent
for (String trustor : this.getDataModel().getMemberList()) {
Double trustValue = this.getConn().getAgentById(trustor).getTrust(playerID);
if (trustValue != null) {
trustSum += trustValue;
numKnownTrustValues++;
}
}
trustFaction = trustSum / numKnownTrustValues;
economic = this.getConn().getAgentById(playerID).getEconomicBelief() - this.getDataModel().getCurrentEconomicPoisition();//change in X
//social = this.getConn().getAgentById(playerID).getSocialBelief() - this.getDataModel().getEstimatedSocialLocation();//change in Y
social = 0.5;
vectorDistance = Math.sqrt(Math.pow(economic, 2) + Math.pow(social, 2));
esFaction = 1 - (vectorDistance / maxDistance);
heuristic = 0.5*trustFaction + 0.5*esFaction;
if (heuristic > 0.5) {
return true;
}
else {
return false;
}
}
| protected boolean respondToJoinRequest(String playerID) {
double heuristic;
//used for the socio-economic faction of heuristic
double vectorDistance;
double maxDistance = Math.sqrt(2);
double economic, social, esFaction;
//used for the trust faction of heuristic
double trustFaction, trustSum = 0;
int numKnownTrustValues = 0;
//Obtain how much trust there is between the memberss of the group and the agent
for (String trustor : this.getDataModel().getMemberList()) {
Double trustValue = this.getConn().getAgentById(trustor).getTrust(playerID);
if (trustValue != null) {
trustSum += trustValue;
numKnownTrustValues++;
}
}
if (numKnownTrustValues == 0) {
return true;//this agent, playerID, wants to make a group of only himself
}
trustFaction = trustSum / numKnownTrustValues;
economic = this.getConn().getAgentById(playerID).getEconomicBelief() - this.getDataModel().getCurrentEconomicPoisition();//change in X
//social = this.getConn().getAgentById(playerID).getSocialBelief() - this.getDataModel().getEstimatedSocialLocation();//change in Y
social = 0.5;
vectorDistance = Math.sqrt(Math.pow(economic, 2) + Math.pow(social, 2));
esFaction = 1 - (vectorDistance / maxDistance);
heuristic = 0.5*trustFaction + 0.5*esFaction;
if (heuristic > 0.5) {
return true;
}
else {
return false;
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
index d4584bf29..801a6d58b 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/tags/TagRefreshButtonArea.java
@@ -1,219 +1,218 @@
/*******************************************************************************
* 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.ui.tags;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.CVSTag;
import org.eclipse.team.internal.ccvs.core.ICVSFolder;
import org.eclipse.team.internal.ccvs.core.util.Assert;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.ccvs.ui.IHelpContextIds;
import org.eclipse.team.internal.ccvs.ui.Policy;
import org.eclipse.team.internal.ui.PixelConverter;
import org.eclipse.team.internal.ui.SWTUtils;
import org.eclipse.team.internal.ui.dialogs.DialogArea;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* An area that displays the Refresh and Configure Tags buttons
*/
public class TagRefreshButtonArea extends DialogArea {
private TagSource tagSource;
private final Shell shell;
private Button refreshButton;
private IRunnableContext context;
private Label fMessageLabel;
public TagRefreshButtonArea(Shell shell, TagSource tagSource) {
Assert.isNotNull(shell);
Assert.isNotNull(tagSource);
this.shell = shell;
this.tagSource = tagSource;
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ui.dialogs.DialogArea#createArea(org.eclipse.swt.widgets.Composite)
*/
public void createArea(Composite parent) {
final String addButtonLabel= Policy.bind("TagConfigurationDialog.21"); //$NON-NLS-1$
final String refreshButtonLabel= Policy.bind("TagConfigurationDialog.20"); //$NON-NLS-1$
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(3, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
- fMessageLabel.setForeground(parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (refreshButtonLabel);
final Button addButton = new Button(buttonComp, SWT.PUSH);
addButton.setText (addButtonLabel);
Dialog.applyDialogFont(buttonComp);
final int buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addButton, refreshButton });
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
addButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
WorkbenchHelp.setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
WorkbenchHelp.setHelp(addButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
public void refresh(final boolean background) {
try {
getRunnableContext().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
setBusy(true);
Display.getDefault().asyncExec(new Runnable() {
public void run() {
fMessageLabel.setText(Policy.bind("TagRefreshButtonArea.6")); //$NON-NLS-1$
}
});
monitor.beginTask(Policy.bind("TagRefreshButtonArea.5"), 100); //$NON-NLS-1$
final CVSTag[] tags = tagSource.refresh(false, Policy.subMonitorFor(monitor, 70));
Display.getDefault().asyncExec(new Runnable() {
public void run() {
fMessageLabel.setText(background && tags.length == 0 ? Policy.bind("TagRefreshButtonArea.7") : ""); //$NON-NLS-1$ //$NON-NLS-2$
}
});
if (!background && promptForBestEffort()) {
tagSource.refresh(true, Policy.subMonitorFor(monitor, 30));
}
} catch (TeamException e) {
throw new InvocationTargetException(e);
} finally {
setBusy(false);
monitor.done();
}
}
});
} catch (InterruptedException e) {
// operation cancelled
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(shell, Policy.bind("TagConfigurationDialog.14"), null, e); //$NON-NLS-1$
}
}
private void setBusy(final boolean busy) {
if (shell != null && !shell.isDisposed())
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
refreshButton.setEnabled(!busy);
}
});
}
/*
* Returns a button that implements the standard refresh tags operation. The
* runnable is run immediatly after the tags are fetched from the server. A
* client should refresh their widgets that show tags because they may of
* changed.
*/
private Button createTagRefreshButton(Composite composite, String title) {
Button refreshButton = new Button(composite, SWT.PUSH);
refreshButton.setText (title);
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
return refreshButton;
}
private boolean promptForBestEffort() {
final boolean[] prompt = new boolean[] { false };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
MessageDialog dialog = new MessageDialog(shell, Policy.bind("TagRefreshButtonArea.0"), null, //$NON-NLS-1$
getNoTagsFoundMessage(),
MessageDialog.INFORMATION,
new String[] {
Policy.bind("TagRefreshButtonArea.1"), //$NON-NLS-1$
Policy.bind("TagRefreshButtonArea.2"), //$NON-NLS-1$
Policy.bind("TagRefreshButtonArea.3") //$NON-NLS-1$
}, 1);
int code = dialog.open();
if (code == 0) {
prompt[0] = true;
} else if (code == 1) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
}
});
return prompt[0];
}
private String getNoTagsFoundMessage() {
return Policy.bind("TagRefreshButtonArea.4", tagSource.getShortDescription()); //$NON-NLS-1$
}
protected static ICVSFolder getSingleFolder(TagSource tagSource) {
if (tagSource instanceof SingleFolderTagSource)
return ((SingleFolderTagSource)tagSource).getFolder();
return null;
}
public TagSource getTagSource() {
return tagSource;
}
public void setTagSource(TagSource tagSource) {
Assert.isNotNull(tagSource);
this.tagSource = tagSource;
}
public IRunnableContext getRunnableContext() {
if (context == null)
return PlatformUI.getWorkbench().getProgressService();
return context;
}
public void setRunnableContext(IRunnableContext context) {
this.context = context;
}
}
| true | true | public void createArea(Composite parent) {
final String addButtonLabel= Policy.bind("TagConfigurationDialog.21"); //$NON-NLS-1$
final String refreshButtonLabel= Policy.bind("TagConfigurationDialog.20"); //$NON-NLS-1$
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(3, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
fMessageLabel.setForeground(parent.getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (refreshButtonLabel);
final Button addButton = new Button(buttonComp, SWT.PUSH);
addButton.setText (addButtonLabel);
Dialog.applyDialogFont(buttonComp);
final int buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addButton, refreshButton });
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
addButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
WorkbenchHelp.setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
WorkbenchHelp.setHelp(addButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
| public void createArea(Composite parent) {
final String addButtonLabel= Policy.bind("TagConfigurationDialog.21"); //$NON-NLS-1$
final String refreshButtonLabel= Policy.bind("TagConfigurationDialog.20"); //$NON-NLS-1$
final PixelConverter converter= SWTUtils.createDialogPixelConverter(parent);
final Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(SWTUtils.createHFillGridData());//SWT.DEFAULT, SWT.DEFAULT, SWT.END, SWT.TOP, false, false));
buttonComp.setLayout(SWTUtils.createGridLayout(3, converter, SWTUtils.MARGINS_NONE));
fMessageLabel= SWTUtils.createLabel(buttonComp, null);
refreshButton = new Button(buttonComp, SWT.PUSH);
refreshButton.setText (refreshButtonLabel);
final Button addButton = new Button(buttonComp, SWT.PUSH);
addButton.setText (addButtonLabel);
Dialog.applyDialogFont(buttonComp);
final int buttonWidth= SWTUtils.calculateControlSize(converter, new Button [] { addButton, refreshButton });
refreshButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
addButton.setLayoutData(SWTUtils.createGridData(buttonWidth, SWT.DEFAULT, SWT.END, SWT.CENTER, false, false));
refreshButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
refresh(false);
}
});
addButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
TagConfigurationDialog d = new TagConfigurationDialog(shell, tagSource);
d.open();
}
});
WorkbenchHelp.setHelp(refreshButton, IHelpContextIds.TAG_CONFIGURATION_REFRESHACTION);
WorkbenchHelp.setHelp(addButton, IHelpContextIds.TAG_CONFIGURATION_OVERVIEW);
Dialog.applyDialogFont(buttonComp);
}
|
diff --git a/src/main/java/org/drools/planner/examples/ras2012/model/MaintenanceWindow.java b/src/main/java/org/drools/planner/examples/ras2012/model/MaintenanceWindow.java
index 81b65c2..60386f4 100644
--- a/src/main/java/org/drools/planner/examples/ras2012/model/MaintenanceWindow.java
+++ b/src/main/java/org/drools/planner/examples/ras2012/model/MaintenanceWindow.java
@@ -1,78 +1,78 @@
package org.drools.planner.examples.ras2012.model;
public class MaintenanceWindow {
private final Node westNode;
private final Node eastNode;
private final long start;
private final long end;
- public MaintenanceWindow(final Node westNode, final Node eastNode, final int time1,
- final int time2) {
+ public MaintenanceWindow(final Node westNode, final Node eastNode, final long time1,
+ final long time2) {
if (eastNode == null || westNode == null) {
throw new IllegalArgumentException("Neither node can be null.");
}
if (eastNode == westNode) {
throw new IllegalArgumentException("MOW must be an arc, not a single node.");
}
if (time1 < 0 || time2 < 0) {
throw new IllegalArgumentException("Neither time can be less than zero.");
}
this.westNode = westNode;
this.eastNode = eastNode;
this.start = Math.min(time1, time2) * 60 * 1000;
this.end = Math.max(time1, time2) * 60 * 1000;
}
public Node getEastNode() {
return this.eastNode;
}
/**
* Get time when this maintenance window ends. (Inclusive.)
*
* @return Time in milliseconds since the beginning of the world.
*/
public long getEnd() {
return this.end;
}
/**
* Get time when this maintenance window starts. (Inclusive.)
*
* @return Time in milliseconds since the beginning of the world.
*/
public long getStart() {
return this.start;
}
public Node getWestNode() {
return this.westNode;
}
/**
* Whether or not the give time is inside the window.
*
* @param time Time in milliseconds.
* @return
*/
public boolean isInside(final long time) {
if (this.start > time) {
return false; // window didn't start yet
}
if (this.end < time) {
return false; // window is already over
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("MaintenanceWindow [startNode=").append(this.westNode).append(", endNode=")
.append(this.eastNode).append(", startingMinute=").append(this.start)
.append(", endingMinute=").append(this.end).append("]");
return builder.toString();
}
}
| true | true | public MaintenanceWindow(final Node westNode, final Node eastNode, final int time1,
final int time2) {
if (eastNode == null || westNode == null) {
throw new IllegalArgumentException("Neither node can be null.");
}
if (eastNode == westNode) {
throw new IllegalArgumentException("MOW must be an arc, not a single node.");
}
if (time1 < 0 || time2 < 0) {
throw new IllegalArgumentException("Neither time can be less than zero.");
}
this.westNode = westNode;
this.eastNode = eastNode;
this.start = Math.min(time1, time2) * 60 * 1000;
this.end = Math.max(time1, time2) * 60 * 1000;
}
| public MaintenanceWindow(final Node westNode, final Node eastNode, final long time1,
final long time2) {
if (eastNode == null || westNode == null) {
throw new IllegalArgumentException("Neither node can be null.");
}
if (eastNode == westNode) {
throw new IllegalArgumentException("MOW must be an arc, not a single node.");
}
if (time1 < 0 || time2 < 0) {
throw new IllegalArgumentException("Neither time can be less than zero.");
}
this.westNode = westNode;
this.eastNode = eastNode;
this.start = Math.min(time1, time2) * 60 * 1000;
this.end = Math.max(time1, time2) * 60 * 1000;
}
|
diff --git a/src/org/jacorb/idl/JacIDL.java b/src/org/jacorb/idl/JacIDL.java
index 4529809b2..e33d143cb 100644
--- a/src/org/jacorb/idl/JacIDL.java
+++ b/src/org/jacorb/idl/JacIDL.java
@@ -1,509 +1,509 @@
/*
* 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.idl;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.util.GlobPatternMapper;
import org.apache.tools.ant.util.SourceFileScanner;
import java.util.*;
import java.io.File;
import java.io.IOException;
/**
* This is the idl compile task for using the idl compiler
* from the ANT build tool.
*
* @author Wei-ju Wu
* @version $Id$
*/
public class JacIDL
extends MatchingTask
{
private File _destdir;
private File _srcdir;
private Path _includepath;
private int _debuglevel;
private boolean _generateir;
private boolean _omgprefix;
private boolean _generateincluded;
private boolean _parseonly;
private boolean _noskel;
private boolean _nostub;
private boolean _sloppyforward;
private boolean _sloppynames;
private boolean _includestate;
private boolean _nofinal;
private boolean _ami_callback;
private boolean _force_overwrite;
private boolean _unchecked_narrow;
private List _defines = new ArrayList();
private List _undefines = new ArrayList();
private File _compileList[] = new File[ 0 ];
private List _i2jpackages = new ArrayList();
private I2JPackageTagHandler i2jHandler = new I2JPackageTagHandler();
public JacIDL()
{
_destdir = new File(".");
_srcdir = new File(".");
_parseonly = false;
_generateir = false;
_noskel = false;
_nostub = false;
_generateincluded = false;
_nofinal = false;
_force_overwrite = false;
_ami_callback = false;
_unchecked_narrow = false;
_debuglevel = 1;
}
/**
* Set the destination directory.
* @param dir the destination directory
*/
public void setDestdir(File dir)
{
_destdir = dir;
}
/**
* Set the source directory.
* @param dir the source directory
*/
public void setSrcdir(File dir)
{
_srcdir = dir;
}
/**
* Set the include path for the idl compiler.
* @param path the include path
*/
public void setIncludepath(Path path)
{
_includepath = path;
}
/**
* Set the debug level.
* @param level the debug level
*/
public void setDebuglevel(int level)
{
_debuglevel = level;
}
// ****************************************************************
// **** Set the flags
// ******************************
/**
* Set the flag to generate the interface repository files.
* @param flag the flag
*/
public void setGenerateir(boolean flag)
{
_generateir = flag;
}
/**
* Set the flag to use the omg package prefix
* @param flag the flag
*/
public void setOmgprefix(boolean flag)
{
_omgprefix = flag;
}
/**
* Set the flag to generate all files.
* @param flag the flag
*/
public void setAll(boolean flag)
{
_generateincluded = flag;
}
/**
* Set the flag to parse the idl only.
* @param flag the flag
*/
public void setParseonly(boolean flag)
{
_parseonly = flag;
}
/**
* Set the flag to leave out skeleton generation.
* @param flag the flag
*/
public void setNoskel(boolean flag)
{
_noskel = flag;
}
/**
* Set the flag to leave out stub generation.
* @param flag the flag
*/
public void setNostub(boolean flag)
{
_nostub = flag;
}
/**
* Set the flag to use sloppy forwards.
* @param flag the flag
*/
public void setSloppyforward(boolean flag)
{
_sloppyforward = flag;
}
/**
* Set the flag to use sloppy names.
* @param flag the flag
*/
public void setSloppynames(boolean flag)
{
_sloppynames = flag;
}
/**
* Setter for 'nofinal' property that indicates whether generated code should have
* a final class definition.
* @param nofinal <code>true</true> for definitions that are not final.
*/
public void setNofinal(boolean flag)
{
_nofinal = flag;
}
/**
* Sets the flag to generate AMI callbacks.
*/
public void setAmi_callback(boolean flag)
{
_ami_callback = flag;
}
/**
* Sets the flag to overwrite existing files.
*/
public void setForceOverwrite(boolean flag)
{
_force_overwrite = flag;
}
/**
* Sets the flag to generated unchecked narrow() calls in stubs
*/
public void setUncheckedNarrow(boolean flag)
{
_unchecked_narrow = flag;
}
// ****************************************************************
// **** Nested elements
// ******************************
public void addDefine(org.apache.tools.ant.types.Environment.Variable
def)
{
// The variable can only be evaluated in the execute() method
_defines.add(def);
}
public void addUndefine(org.apache.tools.ant.types.Environment.Variable
def)
{
// The variable can only be evaluated in the execute() method
_undefines.add(def);
}
/**
* Will be called whenever an <i2jpackage> nested PCDATA element is encountered.
*/
public org.jacorb.idl.JacIDL.I2JPackageTagHandler createI2jpackage()
{
return i2jHandler;
}
/**
* Inner class that will read the i2jpackage tags.
*
* The format for these will be <i2jpackage names="x:y"/>.
* @see #createI2jpackage()
*/
public class I2JPackageTagHandler
{
/**
* Handle the names="packagefrom:packageto" attribute of the i2jpackage element.
* @param names the packagefrom:packageto value.
*/
public void setNames(String names)
{
_i2jpackages.add(names);
}
}
// *****************************************************************
/**
* The execute() method of the task.
* @throws BuildException
*/
public void execute() throws BuildException
{
parser myparser = null;
parser.init ();
// set destination directory
if (! _destdir.exists ())
{
_destdir.mkdirs ();
}
parser.out_dir = _destdir.getPath();
// Generate code for all IDL files, even included ones
parser.generateIncluded = _generateincluded;
// generate interface repository
parser.generateIR = _generateir;
// parse only
parser.parse_only = _parseonly;
// no skeletons
parser.generate_skeletons = (!_noskel);
// no stubs
parser.generate_stubs = (!_nostub);
// sloppy forwards
parser.sloppy = _sloppyforward;
// sloppy names
parser.strict_names = (!_sloppynames);
// nofinal
parser.setGenerateFinalCode(!_nofinal);
// AMI callback model
parser.generate_ami_callback = _ami_callback;
//
parser.forceOverwrite = _force_overwrite;
parser.useUncheckedNarrow = _unchecked_narrow;
// include path
if (_includepath != null)
{
// Check path
String includeList[] = _includepath.list();
for (int i = 0; i < includeList.length; i++)
{
File incDir = project.resolveFile(includeList[ i ]);
if (!incDir.exists())
{
throw new BuildException("include directory \"" +
incDir.getPath() + "\" does not exist !", location);
}
}
GlobalInputStream.setIncludePath(_includepath.toString());
}
// omg package prefix
if (_omgprefix)
{
parser.package_prefix = "org.omg";
}
// Add the i2jpackage values to the parser
for (int i = 0; i < _i2jpackages.size(); i++)
{
parser.addI2JPackage((String) _i2jpackages.get(i));
}
// Set the logging priority
parser.getLogger().setPriority(Environment.intToPriority(_debuglevel));
// setup input file lists
resetFileLists();
DirectoryScanner ds = getDirectoryScanner(_srcdir);
String files[] = ds.getIncludedFiles();
scanFiles(files);
// ***********************************
// **** invoke parser
// ***********************************
// invoke the parser for parsing the files that were
// specified in the task specification
try
{
if (_compileList != null)
{
for (int i = 0; i < _compileList.length; i++)
{
// setup the parser
String fileName = _compileList[ i ].getPath();
log("processing idl file: " + fileName);
GlobalInputStream.init();
GlobalInputStream.setInput(fileName);
lexer.reset();
NameTable.init();
ConstDecl.init();
TypeMap.init();
setupDefines();
myparser = new parser();
myparser.parse();
}
}
}
- catch (IOException ioex)
+ catch (IOException ex)
{
- ioex.printStackTrace();
+ System.err.println(ex);
throw new BuildException();
}
- catch (ParseException pex)
+ catch (ParseException ex)
{
- System.err.println(pex.getMessage());
+ System.err.println(ex);
throw new BuildException();
}
catch (Exception ex)
{
- ex.printStackTrace();
+ System.err.println(ex);
throw new BuildException();
}
}
/**
* Clear the list of files to be compiled and copied..
*/
protected void resetFileLists()
{
_compileList = new File[ 0 ];
}
/**
* Scans the directory looking for source files to be compiled.
* The results are returned in the class variable compileList
*/
protected void scanFiles(String files[]) throws BuildException
{
File file;
// TODO: create an own pattern mapper
GlobPatternMapper m = new GlobPatternMapper();
m.setFrom("*.idl");
m.setTo("*.java");
SourceFileScanner sfs = new SourceFileScanner(this);
File[] newfiles = sfs.restrictAsFiles(files, _srcdir, _destdir, m);
_compileList = new File[ newfiles.length ];
for (int i = 0; i < newfiles.length; i++)
{
log("scan file: " + newfiles[ i ].getPath());
file = newfiles[ i ];
if (!file.exists())
{
throw new BuildException("The input file \"" + file.getPath() +
"\" does not exist !");
}
_compileList[ i ] = file;
}
}
public File[] getFileList()
{
return _compileList;
}
private static boolean fileExists(String filename)
{
if (filename == null || filename.length() == 0) return false;
File file = new File(filename);
return (file.exists() && file.isFile());
}
private static boolean dirExists(File dir)
{
return (dir.exists() && dir.isDirectory());
}
private void setupDefines()
{
org.apache.tools.ant.types.Environment.Variable prop;
String value;
for (int i = 0; i < _defines.size(); i++)
{
prop = (org.apache.tools.ant.types.Environment.Variable)
_defines.get(i);
value = prop.getValue();
if (value == null)
value = "1";
lexer.define(prop.getKey(), value);
}
for (int i = 0; i < _undefines.size(); i++)
{
prop = (org.apache.tools.ant.types.Environment.Variable)
_undefines.get(i);
lexer.undefine(prop.getKey());
}
}
}
| false | true | public void execute() throws BuildException
{
parser myparser = null;
parser.init ();
// set destination directory
if (! _destdir.exists ())
{
_destdir.mkdirs ();
}
parser.out_dir = _destdir.getPath();
// Generate code for all IDL files, even included ones
parser.generateIncluded = _generateincluded;
// generate interface repository
parser.generateIR = _generateir;
// parse only
parser.parse_only = _parseonly;
// no skeletons
parser.generate_skeletons = (!_noskel);
// no stubs
parser.generate_stubs = (!_nostub);
// sloppy forwards
parser.sloppy = _sloppyforward;
// sloppy names
parser.strict_names = (!_sloppynames);
// nofinal
parser.setGenerateFinalCode(!_nofinal);
// AMI callback model
parser.generate_ami_callback = _ami_callback;
//
parser.forceOverwrite = _force_overwrite;
parser.useUncheckedNarrow = _unchecked_narrow;
// include path
if (_includepath != null)
{
// Check path
String includeList[] = _includepath.list();
for (int i = 0; i < includeList.length; i++)
{
File incDir = project.resolveFile(includeList[ i ]);
if (!incDir.exists())
{
throw new BuildException("include directory \"" +
incDir.getPath() + "\" does not exist !", location);
}
}
GlobalInputStream.setIncludePath(_includepath.toString());
}
// omg package prefix
if (_omgprefix)
{
parser.package_prefix = "org.omg";
}
// Add the i2jpackage values to the parser
for (int i = 0; i < _i2jpackages.size(); i++)
{
parser.addI2JPackage((String) _i2jpackages.get(i));
}
// Set the logging priority
parser.getLogger().setPriority(Environment.intToPriority(_debuglevel));
// setup input file lists
resetFileLists();
DirectoryScanner ds = getDirectoryScanner(_srcdir);
String files[] = ds.getIncludedFiles();
scanFiles(files);
// ***********************************
// **** invoke parser
// ***********************************
// invoke the parser for parsing the files that were
// specified in the task specification
try
{
if (_compileList != null)
{
for (int i = 0; i < _compileList.length; i++)
{
// setup the parser
String fileName = _compileList[ i ].getPath();
log("processing idl file: " + fileName);
GlobalInputStream.init();
GlobalInputStream.setInput(fileName);
lexer.reset();
NameTable.init();
ConstDecl.init();
TypeMap.init();
setupDefines();
myparser = new parser();
myparser.parse();
}
}
}
catch (IOException ioex)
{
ioex.printStackTrace();
throw new BuildException();
}
catch (ParseException pex)
{
System.err.println(pex.getMessage());
throw new BuildException();
}
catch (Exception ex)
{
ex.printStackTrace();
throw new BuildException();
}
}
| public void execute() throws BuildException
{
parser myparser = null;
parser.init ();
// set destination directory
if (! _destdir.exists ())
{
_destdir.mkdirs ();
}
parser.out_dir = _destdir.getPath();
// Generate code for all IDL files, even included ones
parser.generateIncluded = _generateincluded;
// generate interface repository
parser.generateIR = _generateir;
// parse only
parser.parse_only = _parseonly;
// no skeletons
parser.generate_skeletons = (!_noskel);
// no stubs
parser.generate_stubs = (!_nostub);
// sloppy forwards
parser.sloppy = _sloppyforward;
// sloppy names
parser.strict_names = (!_sloppynames);
// nofinal
parser.setGenerateFinalCode(!_nofinal);
// AMI callback model
parser.generate_ami_callback = _ami_callback;
//
parser.forceOverwrite = _force_overwrite;
parser.useUncheckedNarrow = _unchecked_narrow;
// include path
if (_includepath != null)
{
// Check path
String includeList[] = _includepath.list();
for (int i = 0; i < includeList.length; i++)
{
File incDir = project.resolveFile(includeList[ i ]);
if (!incDir.exists())
{
throw new BuildException("include directory \"" +
incDir.getPath() + "\" does not exist !", location);
}
}
GlobalInputStream.setIncludePath(_includepath.toString());
}
// omg package prefix
if (_omgprefix)
{
parser.package_prefix = "org.omg";
}
// Add the i2jpackage values to the parser
for (int i = 0; i < _i2jpackages.size(); i++)
{
parser.addI2JPackage((String) _i2jpackages.get(i));
}
// Set the logging priority
parser.getLogger().setPriority(Environment.intToPriority(_debuglevel));
// setup input file lists
resetFileLists();
DirectoryScanner ds = getDirectoryScanner(_srcdir);
String files[] = ds.getIncludedFiles();
scanFiles(files);
// ***********************************
// **** invoke parser
// ***********************************
// invoke the parser for parsing the files that were
// specified in the task specification
try
{
if (_compileList != null)
{
for (int i = 0; i < _compileList.length; i++)
{
// setup the parser
String fileName = _compileList[ i ].getPath();
log("processing idl file: " + fileName);
GlobalInputStream.init();
GlobalInputStream.setInput(fileName);
lexer.reset();
NameTable.init();
ConstDecl.init();
TypeMap.init();
setupDefines();
myparser = new parser();
myparser.parse();
}
}
}
catch (IOException ex)
{
System.err.println(ex);
throw new BuildException();
}
catch (ParseException ex)
{
System.err.println(ex);
throw new BuildException();
}
catch (Exception ex)
{
System.err.println(ex);
throw new BuildException();
}
}
|
diff --git a/src/de/danoeh/antennapod/util/URLChecker.java b/src/de/danoeh/antennapod/util/URLChecker.java
index 6d9b8ff0..13668d4a 100644
--- a/src/de/danoeh/antennapod/util/URLChecker.java
+++ b/src/de/danoeh/antennapod/util/URLChecker.java
@@ -1,34 +1,33 @@
package de.danoeh.antennapod.util;
import android.util.Log;
import de.danoeh.antennapod.AppConfig;
/** Provides methods for checking and editing a URL.*/
public final class URLChecker {
/**Class shall not be instantiated.*/
private URLChecker() {
}
/**Logging tag.*/
private static final String TAG = "URLChecker";
/** Checks if URL is valid and modifies it if necessary.
* @param url The url which is going to be prepared
* @return The prepared url
* */
public static String prepareURL(String url) {
StringBuilder builder = new StringBuilder();
- url = url.trim();
- if (!url.startsWith("http")) {
+ if (url.startsWith("feed://")) {
+ if (AppConfig.DEBUG) Log.d(TAG, "Replacing feed:// with http://");
+ url = url.replace("feed://", "http://");
+ } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
+ if (AppConfig.DEBUG) Log.d(TAG, "Adding http:// at the beginning of the URL");
builder.append("http://");
- if (AppConfig.DEBUG) Log.d(TAG, "Missing http; appending");
- } else if (url.startsWith("https")) {
- if (AppConfig.DEBUG) Log.d(TAG, "Replacing https with http");
- url = url.replaceFirst("https", "http");
}
builder.append(url);
return builder.toString();
}
}
| false | true | public static String prepareURL(String url) {
StringBuilder builder = new StringBuilder();
url = url.trim();
if (!url.startsWith("http")) {
builder.append("http://");
if (AppConfig.DEBUG) Log.d(TAG, "Missing http; appending");
} else if (url.startsWith("https")) {
if (AppConfig.DEBUG) Log.d(TAG, "Replacing https with http");
url = url.replaceFirst("https", "http");
}
builder.append(url);
return builder.toString();
}
| public static String prepareURL(String url) {
StringBuilder builder = new StringBuilder();
if (url.startsWith("feed://")) {
if (AppConfig.DEBUG) Log.d(TAG, "Replacing feed:// with http://");
url = url.replace("feed://", "http://");
} else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
if (AppConfig.DEBUG) Log.d(TAG, "Adding http:// at the beginning of the URL");
builder.append("http://");
}
builder.append(url);
return builder.toString();
}
|
diff --git a/wf-server/src/main/java/ru/taskurotta/server/json/ObjectFactory.java b/wf-server/src/main/java/ru/taskurotta/server/json/ObjectFactory.java
index 4522577b..7ecc8be0 100644
--- a/wf-server/src/main/java/ru/taskurotta/server/json/ObjectFactory.java
+++ b/wf-server/src/main/java/ru/taskurotta/server/json/ObjectFactory.java
@@ -1,277 +1,277 @@
package ru.taskurotta.server.json;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.taskurotta.backend.storage.model.ArgContainer;
import ru.taskurotta.backend.storage.model.DecisionContainer;
import ru.taskurotta.backend.storage.model.ErrorContainer;
import ru.taskurotta.backend.storage.model.TaskContainer;
import ru.taskurotta.backend.storage.model.TaskOptionsContainer;
import ru.taskurotta.core.Promise;
import ru.taskurotta.core.Task;
import ru.taskurotta.core.TaskDecision;
import ru.taskurotta.core.TaskOptions;
import ru.taskurotta.core.TaskTarget;
import ru.taskurotta.internal.core.TaskImpl;
import ru.taskurotta.internal.core.TaskTargetImpl;
import ru.taskurotta.util.ActorDefinition;
import ru.taskurotta.util.ActorUtils;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.UUID;
/**
* User: romario
* Date: 2/25/13
* Time: 4:20 PM
*/
public class ObjectFactory {
private static final Logger logger = LoggerFactory.getLogger(ObjectFactory.class);
private ObjectMapper mapper;
public ObjectFactory() {
mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
}
public Object parseArg(ArgContainer argContainer) {
if (argContainer == null) {
return null;
}
Object value = null;
String json = argContainer.getJSONValue();
if (json != null) {
String className = argContainer.getClassName();
try {
value = argContainer.isArray()? getArrayValue(json, className): getSimpleValue(json, className);
} catch (Exception e) {
// TODO: create new RuntimeException type
throw new RuntimeException("Can not instantiate Object from json. JSON value: " + argContainer.getJSONValue(), e);
}
} else {
ArgContainer[] compositeValue = argContainer.getCompositeValue();
if (null != compositeValue) {
try {
value = Array.newInstance(Class.forName(argContainer.getClassName()), compositeValue.length);
for (int i = 0; i < compositeValue.length; i++) {
Array.set(value, i, parseArg(compositeValue[i]));
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Can not instantiate ObjectArray", e);
}
}
}
if (argContainer.isPromise()) {
Promise promise = Promise.createInstance(argContainer.getTaskId());
if (argContainer.isReady()) {
//noinspection unchecked
promise.set(value);
}
return promise;
}
return value;
}
private Object getSimpleValue(String json, String valueClass) throws ClassNotFoundException, IOException {
Class loadedClass = Thread.currentThread().getContextClassLoader().loadClass(valueClass);
return mapper.readValue(json, loadedClass);
}
private Object getArrayValue(String json, String arrayItemClassName) throws Exception {
JsonNode node = mapper.readTree(json);
ObjectCodec objectCodec = mapper.treeAsTokens(node).getCodec();
Object array = ArrayFactory.newInstance(arrayItemClassName, node.size());
Class<?> componentType = array.getClass().getComponentType();
for (int i = 0; i < node.size(); i++) {
Array.set(array, i, objectCodec.treeToValue(node.get(i), componentType));
}
return array;
}
public ArgContainer dumpArg(Object arg) {
if (arg == null) {
return null;
}
ArgContainer.ValueType type = ArgContainer.ValueType.PLAIN;
UUID taskId = null;
- boolean isReady = false;
+ boolean isReady = true;
if (arg instanceof Promise) {
type = ArgContainer.ValueType.PROMISE;
taskId = ((Promise) arg).getId();
isReady = ((Promise) arg).isReady();
arg = isReady? ((Promise) arg).get() : null;
}
ArgContainer result;
String className = null;
String jsonValue = null;
if (arg != null) {
try {
if (arg.getClass().isArray()) {
className = arg.getClass().getComponentType().getName();
if (arg.getClass().getComponentType().isAssignableFrom(Promise.class)) {
type = ArgContainer.ValueType.OBJECT_ARRAY;
ArgContainer[] compositeValue = writeAsObjectArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, compositeValue);
} else {
type = ArgContainer.ValueType.ARRAY;
jsonValue = writeAsArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} else {
className = arg.getClass().getName();
jsonValue = mapper.writeValueAsString(arg);
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} catch (JsonProcessingException e) {
// TODO: create new RuntimeException type
throw new RuntimeException("Can not create json String from Object: " + arg, e);
}
} else {
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
logger.debug("Created new ArgContainer[{}]", result);
return result;
}
public Task parseTask(TaskContainer taskContainer) {
if (taskContainer == null) {
return null;
}
UUID processId = taskContainer.getProcessId();
UUID taskId = taskContainer.getTaskId();
ActorDefinition actorDef = ActorUtils.getActorDefinition(taskContainer.getActorId());
TaskTarget taskTarget = new TaskTargetImpl(taskContainer.getType(), actorDef.getName(), actorDef.getVersion(), taskContainer.getMethod());
Object[] args = null;
ArgContainer[] argContainers = taskContainer.getArgs();
if (argContainers != null) {
args = new Object[argContainers.length];
int i = 0;
for (ArgContainer argContainer : argContainers) {
args[i++] = parseArg(argContainer);
}
}
return new TaskImpl(taskId, processId, taskTarget, taskContainer.getStartTime(), taskContainer.getNumberOfAttempts(), args, null);
}
public TaskContainer dumpTask(Task task) {
UUID taskId = task.getId();
UUID processId = task.getProcessId();
TaskTarget target = task.getTarget();
ArgContainer[] argContainers = null;
Object[] args = task.getArgs();
if (args != null) {
argContainers = new ArgContainer[args.length];
int i = 0;
for (Object arg : args) {
argContainers[i++] = dumpArg(arg);
}
}
TaskOptionsContainer taskOptionsContainer = dumpTaskOptions(task.getTaskOptions());
return new TaskContainer(taskId, processId, target.getMethod(), ActorUtils.getActorId(target),
target.getType(), task.getStartTime(), task.getNumberOfAttempts(), argContainers, taskOptionsContainer);
}
public TaskOptionsContainer dumpTaskOptions(TaskOptions taskOptions) {
if (taskOptions == null) {
return null;
}
return new TaskOptionsContainer(taskOptions.getArgTypes());
}
public DecisionContainer dumpResult(TaskDecision taskDecision) {
UUID taskId = taskDecision.getId();
UUID processId = taskDecision.getProcessId();
ArgContainer value = dumpArg(taskDecision.getValue());
ErrorContainer errorContainer = dumpError(taskDecision.getException());
TaskContainer[] taskContainers = null;
Task[] tasks = taskDecision.getTasks();
if (tasks != null) {
taskContainers = new TaskContainer[tasks.length];
int i = 0;
for (Task task : tasks) {
taskContainers[i++] = dumpTask(task);
}
}
return new DecisionContainer(taskId, processId, value, errorContainer, taskDecision.getRestartTime(), taskContainers);
}
public ErrorContainer dumpError(Throwable e) {
if (e == null) {
return null;
}
return new ErrorContainer(e);
}
private String writeAsArray(Object array) throws JsonProcessingException {
ArrayNode arrayNode = mapper.createArrayNode();
if (array != null) {
int size = Array.getLength(array);
for (int i = 0; i<size; i++) {
String itemValue = mapper.writeValueAsString(Array.get(array, i));
arrayNode.add(itemValue);
}
}
return arrayNode.toString();
}
private ArgContainer[] writeAsObjectArray(Object array) throws JsonProcessingException {
ArgContainer[] result = null;
if (array != null) {
int size = Array.getLength(array);
result = new ArgContainer[size];
for (int i = 0; i<size; i++) {
result[i] = dumpArg(Array.get(array, i));
}
}
return result;
}
}
| true | true | public ArgContainer dumpArg(Object arg) {
if (arg == null) {
return null;
}
ArgContainer.ValueType type = ArgContainer.ValueType.PLAIN;
UUID taskId = null;
boolean isReady = false;
if (arg instanceof Promise) {
type = ArgContainer.ValueType.PROMISE;
taskId = ((Promise) arg).getId();
isReady = ((Promise) arg).isReady();
arg = isReady? ((Promise) arg).get() : null;
}
ArgContainer result;
String className = null;
String jsonValue = null;
if (arg != null) {
try {
if (arg.getClass().isArray()) {
className = arg.getClass().getComponentType().getName();
if (arg.getClass().getComponentType().isAssignableFrom(Promise.class)) {
type = ArgContainer.ValueType.OBJECT_ARRAY;
ArgContainer[] compositeValue = writeAsObjectArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, compositeValue);
} else {
type = ArgContainer.ValueType.ARRAY;
jsonValue = writeAsArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} else {
className = arg.getClass().getName();
jsonValue = mapper.writeValueAsString(arg);
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} catch (JsonProcessingException e) {
// TODO: create new RuntimeException type
throw new RuntimeException("Can not create json String from Object: " + arg, e);
}
} else {
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
logger.debug("Created new ArgContainer[{}]", result);
return result;
}
| public ArgContainer dumpArg(Object arg) {
if (arg == null) {
return null;
}
ArgContainer.ValueType type = ArgContainer.ValueType.PLAIN;
UUID taskId = null;
boolean isReady = true;
if (arg instanceof Promise) {
type = ArgContainer.ValueType.PROMISE;
taskId = ((Promise) arg).getId();
isReady = ((Promise) arg).isReady();
arg = isReady? ((Promise) arg).get() : null;
}
ArgContainer result;
String className = null;
String jsonValue = null;
if (arg != null) {
try {
if (arg.getClass().isArray()) {
className = arg.getClass().getComponentType().getName();
if (arg.getClass().getComponentType().isAssignableFrom(Promise.class)) {
type = ArgContainer.ValueType.OBJECT_ARRAY;
ArgContainer[] compositeValue = writeAsObjectArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, compositeValue);
} else {
type = ArgContainer.ValueType.ARRAY;
jsonValue = writeAsArray(arg) ;
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} else {
className = arg.getClass().getName();
jsonValue = mapper.writeValueAsString(arg);
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
} catch (JsonProcessingException e) {
// TODO: create new RuntimeException type
throw new RuntimeException("Can not create json String from Object: " + arg, e);
}
} else {
result = new ArgContainer(className, type, taskId, isReady, jsonValue);
}
logger.debug("Created new ArgContainer[{}]", result);
return result;
}
|
diff --git a/src/com/android/providers/downloads/DownloadNotifier.java b/src/com/android/providers/downloads/DownloadNotifier.java
index daae783..f387865 100644
--- a/src/com/android/providers/downloads/DownloadNotifier.java
+++ b/src/com/android/providers/downloads/DownloadNotifier.java
@@ -1,318 +1,322 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.downloads;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.provider.Downloads;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.annotation.concurrent.GuardedBy;
/**
* Update {@link NotificationManager} to reflect current {@link DownloadInfo}
* states. Collapses similar downloads into a single notification, and builds
* {@link PendingIntent} that launch towards {@link DownloadReceiver}.
*/
public class DownloadNotifier {
private static final int TYPE_ACTIVE = 1;
private static final int TYPE_WAITING = 2;
private static final int TYPE_COMPLETE = 3;
private final Context mContext;
private final NotificationManager mNotifManager;
/**
* Currently active notifications, mapped from clustering tag to timestamp
* when first shown.
*
* @see #buildNotificationTag(DownloadInfo)
*/
@GuardedBy("mActiveNotifs")
private final HashMap<String, Long> mActiveNotifs = Maps.newHashMap();
public DownloadNotifier(Context context) {
mContext = context;
mNotifManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
}
public void cancelAll() {
mNotifManager.cancelAll();
}
/**
* Update {@link NotificationManager} to reflect the given set of
* {@link DownloadInfo}, adding, collapsing, and removing as needed.
*/
public void updateWith(Collection<DownloadInfo> downloads) {
synchronized (mActiveNotifs) {
updateWithLocked(downloads);
}
}
private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
+ // build a synthetic uri for intent identification purposes
+ final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
final Intent intent = new Intent(Constants.ACTION_LIST,
- null, mContext, DownloadReceiver.class);
+ uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
- builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
+ builder.setContentIntent(PendingIntent.getBroadcast(mContext,
+ 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
- builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
+ builder.setContentIntent(PendingIntent.getBroadcast(mContext,
+ 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
final DownloadHandler handler = DownloadHandler.getInstance();
long current = 0;
long total = 0;
long speed = 0;
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += handler.getCurrentSpeed(info.mId);
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
private static CharSequence getDownloadTitle(Resources res, DownloadInfo info) {
if (!TextUtils.isEmpty(info.mTitle)) {
return info.mTitle;
} else {
return res.getString(R.string.download_unknown_title);
}
}
private long[] getDownloadIds(Collection<DownloadInfo> infos) {
final long[] ids = new long[infos.size()];
int i = 0;
for (DownloadInfo info : infos) {
ids[i++] = info.mId;
}
return ids;
}
/**
* Build tag used for collapsing several {@link DownloadInfo} into a single
* {@link Notification}.
*/
private static String buildNotificationTag(DownloadInfo info) {
if (info.mStatus == Downloads.Impl.STATUS_QUEUED_FOR_WIFI) {
return TYPE_WAITING + ":" + info.mPackage;
} else if (isActiveAndVisible(info)) {
return TYPE_ACTIVE + ":" + info.mPackage;
} else if (isCompleteAndVisible(info)) {
// Complete downloads always have unique notifs
return TYPE_COMPLETE + ":" + info.mId;
} else {
return null;
}
}
/**
* Return the cluster type of the given tag, as created by
* {@link #buildNotificationTag(DownloadInfo)}.
*/
private static int getNotificationTagType(String tag) {
return Integer.parseInt(tag.substring(0, tag.indexOf(':')));
}
private static boolean isActiveAndVisible(DownloadInfo download) {
return Downloads.Impl.isStatusInformational(download.mStatus) &&
(download.mVisibility == VISIBILITY_VISIBLE
|| download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
private static boolean isCompleteAndVisible(DownloadInfo download) {
return Downloads.Impl.isStatusCompleted(download.mStatus) &&
(download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED
|| download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
}
}
| false | true | private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
final Intent intent = new Intent(Constants.ACTION_LIST,
null, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
final DownloadHandler handler = DownloadHandler.getInstance();
long current = 0;
long total = 0;
long speed = 0;
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += handler.getCurrentSpeed(info.mId);
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
| private void updateWithLocked(Collection<DownloadInfo> downloads) {
final Resources res = mContext.getResources();
// Cluster downloads together
final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
for (DownloadInfo info : downloads) {
final String tag = buildNotificationTag(info);
if (tag != null) {
clustered.put(tag, info);
}
}
// Build notification for each cluster
for (String tag : clustered.keySet()) {
final int type = getNotificationTagType(tag);
final Collection<DownloadInfo> cluster = clustered.get(tag);
final Notification.Builder builder = new Notification.Builder(mContext);
// Use time when cluster was first shown to avoid shuffling
final long firstShown;
if (mActiveNotifs.containsKey(tag)) {
firstShown = mActiveNotifs.get(tag);
} else {
firstShown = System.currentTimeMillis();
mActiveNotifs.put(tag, firstShown);
}
builder.setWhen(firstShown);
// Show relevant icon
if (type == TYPE_ACTIVE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download);
} else if (type == TYPE_WAITING) {
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
} else if (type == TYPE_COMPLETE) {
builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
}
// Build action intents
if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
// build a synthetic uri for intent identification purposes
final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
final Intent intent = new Intent(Constants.ACTION_LIST,
uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setOngoing(true);
} else if (type == TYPE_COMPLETE) {
final DownloadInfo info = cluster.iterator().next();
final Uri uri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
final String action;
if (Downloads.Impl.isStatusError(info.mStatus)) {
action = Constants.ACTION_LIST;
} else {
if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
action = Constants.ACTION_OPEN;
} else {
action = Constants.ACTION_LIST;
}
}
final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
getDownloadIds(cluster));
builder.setContentIntent(PendingIntent.getBroadcast(mContext,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
uri, mContext, DownloadReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
}
// Calculate and show progress
String remainingText = null;
String percentText = null;
if (type == TYPE_ACTIVE) {
final DownloadHandler handler = DownloadHandler.getInstance();
long current = 0;
long total = 0;
long speed = 0;
for (DownloadInfo info : cluster) {
if (info.mTotalBytes != -1) {
current += info.mCurrentBytes;
total += info.mTotalBytes;
speed += handler.getCurrentSpeed(info.mId);
}
}
if (total > 0) {
final int percent = (int) ((current * 100) / total);
percentText = res.getString(R.string.download_percent, percent);
if (speed > 0) {
final long remainingMillis = ((total - current) * 1000) / speed;
remainingText = res.getString(R.string.download_remaining,
DateUtils.formatDuration(remainingMillis));
}
builder.setProgress(100, percent, false);
} else {
builder.setProgress(100, 0, true);
}
}
// Build titles and description
final Notification notif;
if (cluster.size() == 1) {
final DownloadInfo info = cluster.iterator().next();
builder.setContentTitle(getDownloadTitle(res, info));
if (type == TYPE_ACTIVE) {
if (!TextUtils.isEmpty(info.mDescription)) {
builder.setContentText(info.mDescription);
} else {
builder.setContentText(remainingText);
}
builder.setContentInfo(percentText);
} else if (type == TYPE_WAITING) {
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
} else if (type == TYPE_COMPLETE) {
if (Downloads.Impl.isStatusError(info.mStatus)) {
builder.setContentText(res.getText(R.string.notification_download_failed));
} else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
builder.setContentText(
res.getText(R.string.notification_download_complete));
}
}
notif = builder.build();
} else {
final Notification.InboxStyle inboxStyle = new Notification.InboxStyle(builder);
for (DownloadInfo info : cluster) {
inboxStyle.addLine(getDownloadTitle(res, info));
}
if (type == TYPE_ACTIVE) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_active, cluster.size(), cluster.size()));
builder.setContentText(remainingText);
builder.setContentInfo(percentText);
inboxStyle.setSummaryText(remainingText);
} else if (type == TYPE_WAITING) {
builder.setContentTitle(res.getQuantityString(
R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
builder.setContentText(
res.getString(R.string.notification_need_wifi_for_size));
inboxStyle.setSummaryText(
res.getString(R.string.notification_need_wifi_for_size));
}
notif = inboxStyle.build();
}
mNotifManager.notify(tag, 0, notif);
}
// Remove stale tags that weren't renewed
final Iterator<String> it = mActiveNotifs.keySet().iterator();
while (it.hasNext()) {
final String tag = it.next();
if (!clustered.containsKey(tag)) {
mNotifManager.cancel(tag, 0);
it.remove();
}
}
}
|
diff --git a/tools/eclipslee/plugin/plugins/org.mobicents.eclipslee.servicecreation/src/org/mobicents/eclipslee/servicecreation/popup/actions/EditSbbEventsAction.java b/tools/eclipslee/plugin/plugins/org.mobicents.eclipslee.servicecreation/src/org/mobicents/eclipslee/servicecreation/popup/actions/EditSbbEventsAction.java
index 2cc4dffe9..c4f7dd175 100644
--- a/tools/eclipslee/plugin/plugins/org.mobicents.eclipslee.servicecreation/src/org/mobicents/eclipslee/servicecreation/popup/actions/EditSbbEventsAction.java
+++ b/tools/eclipslee/plugin/plugins/org.mobicents.eclipslee.servicecreation/src/org/mobicents/eclipslee/servicecreation/popup/actions/EditSbbEventsAction.java
@@ -1,414 +1,415 @@
/**
* Copyright 2005 Open Cloud Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mobicents.eclipslee.servicecreation.popup.actions;
import java.util.HashMap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.mobicents.eclipslee.servicecreation.util.ClassUtil;
import org.mobicents.eclipslee.servicecreation.util.EclipseUtil;
import org.mobicents.eclipslee.servicecreation.util.SbbFinder;
import org.mobicents.eclipslee.servicecreation.wizards.sbb.SbbEventsDialog;
import org.mobicents.eclipslee.util.SLEE;
import org.mobicents.eclipslee.util.Utils;
import org.mobicents.eclipslee.util.slee.xml.components.ComponentNotFoundException;
import org.mobicents.eclipslee.util.slee.xml.components.EventXML;
import org.mobicents.eclipslee.util.slee.xml.components.SbbEventXML;
import org.mobicents.eclipslee.util.slee.xml.components.SbbXML;
import org.mobicents.eclipslee.xml.EventJarXML;
import org.mobicents.eclipslee.xml.SbbJarXML;
/**
* @author cath
*/
public class EditSbbEventsAction implements IActionDelegate {
public EditSbbEventsAction() {
}
public EditSbbEventsAction(String sbbID) {
this.sbbID = sbbID;
}
public void setActivePart(IAction action, IWorkbenchPart targetPart) {}
public void run(IAction action) {
initialize();
if (dialog == null) {
MessageDialog.openError(new Shell(), "Error Modifying Service Building Block", getLastError());
return;
}
if (dialog.open() == Window.OK) {
try {
IProgressMonitor monitor = null;
HashMap newEvents[] = dialog.getSelectedEvents();
// foreach event in xml
// if not in newEvents
// delete event from xml and sbb abstract class
SbbEventXML oldEvents[] = sbb.getEvents();
for (int old = 0; old < oldEvents.length; old++) {
SbbEventXML oldEvent = oldEvents[old];
if (findEvent(oldEvent, newEvents) == null) {
// Nuke this event.
String scopedName = oldEvent.getScopedName();
sbb.removeEvent(oldEvent);
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "fire" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
// foreach new event
// if getEvent(name, vendor, version) -- update
// else createEvent -- make receive, fire, ies methods
for (int i = 0; i < newEvents.length; i++) {
HashMap event = newEvents[i];
EventJarXML eventJarXML = (EventJarXML) event.get("XML");
EventXML eventXML = eventJarXML.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
SbbEventXML sbbEventXML = sbb.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
String scopedName = (String) event.get("Scoped Name");
String direction = (String) event.get("Direction");
boolean initialEvent = ((Boolean) event.get("Initial Event")).booleanValue();
String [] selectors = (String []) event.get("Initial Event Selectors");
if (sbbEventXML == null) {
sbbEventXML = sbb.addEvent(eventXML);
if(scopedName == null) {
scopedName = ((String) event.get("Name"));
scopedName = scopedName.substring(scopedName.lastIndexOf('.') + 1);
}
scopedName = scopedName.substring(0, 1).toUpperCase() + scopedName.substring(1);
sbbEventXML.setScopedName(scopedName);
sbbEventXML.setEventDirection(direction);
sbbEventXML.setInitialEvent(initialEvent);
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
} else {
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
if (direction.indexOf("Receive") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n");
if (direction.indexOf("Fire") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);");
} else {
// Modify the existing event.
String oldDirection = sbbEventXML.getEventDirection();
String oldScopedName = sbbEventXML.getScopedName();
// Deal with any changes in event direction
if (!oldDirection.equals(direction)) {
// Direction has changed.
if (direction.indexOf("Fire") == -1) {
// Nuke any fire method.
ClassUtil.removeMethodFromClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName));
} else {
// Create a fire method
if (oldDirection.indexOf("Fire") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);\n\n");
}
if (direction.indexOf("Receive") == -1) {
// nuke any receive method
ClassUtil.removeMethodFromClass(abstractFile,
"on" + Utils.capitalize(oldScopedName));
} else {
// Create the event handler
if (oldDirection.indexOf("Receive") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n\n");
}
sbbEventXML.setEventDirection(direction);
}
// Is this an initial event?
sbbEventXML.setInitialEvent(initialEvent);
// Remove old initial event selectors (N.B. not custom IES)
String oldSelectors[] = sbbEventXML.getInitialEventSelectors();
for (int j = 0; j < oldSelectors.length; j++) {
sbbEventXML.removeInitialEventSelector(oldSelectors[j]);
}
// Add new initial event selectors (N.B. not custom IES)
boolean customIES = false;
if (initialEvent) {
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
customIES = true; // For next part.
continue;
}
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
// Deal with the IES -- first was there one originally
String oldIESMethod = sbbEventXML.getInitialEventSelectorMethod();
// Secondly, do we need one now?
if (oldIESMethod != null && customIES == false) {
// Nuke the IES
sbbEventXML.setInitialEventSelectorMethod(null);
ClassUtil.removeMethodFromClass(abstractFile, oldIESMethod);
} else {
if (oldIESMethod == null && customIES == true) {
// Create the IES
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
}
}
// Deal with any change in the scoped name.
if (!oldScopedName.equals(scopedName)) {
sbbEventXML.setScopedName(scopedName);
+ sbbEventXML.setInitialEventSelectorMethod("on" + Utils.capitalize(scopedName) + "InitialEventSelect");
// Rename the fire, receive and ies methods if they exist.
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName),
"on" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName),
"fire" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName) + "InitialEventSelect",
- "on" + Utils.capitalize(scopedName) + "InitialEventSelect");
+ "on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
}
// Save the XML
xmlFile.setContents(sbbJarXML.getInputStreamFromXML(), true, true, monitor);
} catch (Exception e) {
MessageDialog.openError(new Shell(), "Error Modifying SBB", "An error occurred while modifying the service building block. It must be modified manually.");
e.printStackTrace();
System.err.println(e.toString() + ": " + e.getMessage());
return;
}
}
}
/**
* Get the SBBXML data object for the current selection.
*
*/
private void initialize() {
String projectName = null;
sbb = null;
sbbJarXML = null;
if (selection == null && selection.isEmpty()) {
setLastError("Please select an SBB's Java or XML file first.");
return;
}
if (!(selection instanceof IStructuredSelection)) {
setLastError("Please select an SBB's Java or XML file first.");
return;
}
IStructuredSelection ssel = (IStructuredSelection) selection;
if (ssel.size() > 1) {
setLastError("This plugin only supports editing of one service building block at a time.");
return;
}
// Get the first (and only) item in the selection.
Object obj = ssel.getFirstElement();
if (obj instanceof IFile) {
ICompilationUnit unit = null;
try {
unit = JavaCore.createCompilationUnitFrom((IFile) obj);
} catch (Exception e) {
// Suppress Exception. The next check checks for null unit.
}
if (unit != null) { // .java file
sbbJarXML = SbbFinder.getSbbJarXML(unit);
if (sbbJarXML == null) {
setLastError("Unable to find the corresponding sbb-jar.xml for this SBB.");
return;
}
try {
sbb = sbbJarXML.getSbb(EclipseUtil.getClassName(unit));
} catch (org.mobicents.eclipslee.util.slee.xml.components.ComponentNotFoundException e) {
setLastError("Unable to find the corresponding sbb-jar.xml for this SBB.");
return;
}
// Set 'file' to the SBB XML file, not the Java file.
xmlFile = SbbFinder.getSbbJarXMLFile(unit);
abstractFile = SbbFinder.getSbbAbstractClassFile(unit);
if (xmlFile == null) {
setLastError("Unable to find SBB XML.");
return;
}
if (abstractFile == null) {
setLastError("Unable to find SBB abstract class file.");
return;
}
projectName = unit.getJavaProject().getProject().getName();
} else {
IFile file = (IFile) obj;
String name = SLEE.getName(sbbID);
String vendor = SLEE.getVendor(sbbID);
String version = SLEE.getVersion(sbbID);
try {
sbbJarXML = new SbbJarXML(file);
} catch (Exception e) {
setLastError("Unable to find the corresponding sbb-jar.xml for this SBB.");
return;
}
try {
sbb = sbbJarXML.getSbb(name, vendor, version);
} catch (ComponentNotFoundException e) {
setLastError("This SBB is not defined in this XML file.");
return;
}
xmlFile = file;
abstractFile = SbbFinder.getSbbAbstractClassFile(xmlFile, name, vendor, version);
if (abstractFile == null) {
setLastError("Unable to find SBB abstract class file.");
return;
}
unit = (ICompilationUnit) JavaCore.create(abstractFile);
projectName = unit.getJavaProject().getProject().getName();
}
} else {
setLastError("Unsupported object type: " + obj.getClass().toString());
return;
}
SbbEventXML[] events = sbb.getEvents();
dialog = new SbbEventsDialog(new Shell(), events, projectName);
return;
}
/**
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
this.selection = selection;
}
private void setLastError(String error) {
if (error == null) {
lastError = "Success";
} else {
lastError = error;
}
}
private String getLastError() {
String error = lastError;
setLastError(null);
return error;
}
private HashMap findEvent(SbbEventXML event, HashMap selectedEvents[]) {
for (int i = 0; i < selectedEvents.length; i++) {
String name = (String) selectedEvents[i].get("Name");
String vendor = (String) selectedEvents[i].get("Vendor");
String version = (String) selectedEvents[i].get("Version");
if (event.getName().equals(name)
&& event.getVendor().equals(vendor)
&& event.getVersion().equals(version)) {
return selectedEvents[i];
}
}
return null;
}
private String sbbID;
private SbbJarXML sbbJarXML;
private SbbXML sbb;
private String lastError;
private ISelection selection;
private SbbEventsDialog dialog;
private IFile xmlFile;
private IFile abstractFile;
}
| false | true | public void run(IAction action) {
initialize();
if (dialog == null) {
MessageDialog.openError(new Shell(), "Error Modifying Service Building Block", getLastError());
return;
}
if (dialog.open() == Window.OK) {
try {
IProgressMonitor monitor = null;
HashMap newEvents[] = dialog.getSelectedEvents();
// foreach event in xml
// if not in newEvents
// delete event from xml and sbb abstract class
SbbEventXML oldEvents[] = sbb.getEvents();
for (int old = 0; old < oldEvents.length; old++) {
SbbEventXML oldEvent = oldEvents[old];
if (findEvent(oldEvent, newEvents) == null) {
// Nuke this event.
String scopedName = oldEvent.getScopedName();
sbb.removeEvent(oldEvent);
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "fire" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
// foreach new event
// if getEvent(name, vendor, version) -- update
// else createEvent -- make receive, fire, ies methods
for (int i = 0; i < newEvents.length; i++) {
HashMap event = newEvents[i];
EventJarXML eventJarXML = (EventJarXML) event.get("XML");
EventXML eventXML = eventJarXML.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
SbbEventXML sbbEventXML = sbb.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
String scopedName = (String) event.get("Scoped Name");
String direction = (String) event.get("Direction");
boolean initialEvent = ((Boolean) event.get("Initial Event")).booleanValue();
String [] selectors = (String []) event.get("Initial Event Selectors");
if (sbbEventXML == null) {
sbbEventXML = sbb.addEvent(eventXML);
if(scopedName == null) {
scopedName = ((String) event.get("Name"));
scopedName = scopedName.substring(scopedName.lastIndexOf('.') + 1);
}
scopedName = scopedName.substring(0, 1).toUpperCase() + scopedName.substring(1);
sbbEventXML.setScopedName(scopedName);
sbbEventXML.setEventDirection(direction);
sbbEventXML.setInitialEvent(initialEvent);
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
} else {
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
if (direction.indexOf("Receive") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n");
if (direction.indexOf("Fire") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);");
} else {
// Modify the existing event.
String oldDirection = sbbEventXML.getEventDirection();
String oldScopedName = sbbEventXML.getScopedName();
// Deal with any changes in event direction
if (!oldDirection.equals(direction)) {
// Direction has changed.
if (direction.indexOf("Fire") == -1) {
// Nuke any fire method.
ClassUtil.removeMethodFromClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName));
} else {
// Create a fire method
if (oldDirection.indexOf("Fire") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);\n\n");
}
if (direction.indexOf("Receive") == -1) {
// nuke any receive method
ClassUtil.removeMethodFromClass(abstractFile,
"on" + Utils.capitalize(oldScopedName));
} else {
// Create the event handler
if (oldDirection.indexOf("Receive") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n\n");
}
sbbEventXML.setEventDirection(direction);
}
// Is this an initial event?
sbbEventXML.setInitialEvent(initialEvent);
// Remove old initial event selectors (N.B. not custom IES)
String oldSelectors[] = sbbEventXML.getInitialEventSelectors();
for (int j = 0; j < oldSelectors.length; j++) {
sbbEventXML.removeInitialEventSelector(oldSelectors[j]);
}
// Add new initial event selectors (N.B. not custom IES)
boolean customIES = false;
if (initialEvent) {
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
customIES = true; // For next part.
continue;
}
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
// Deal with the IES -- first was there one originally
String oldIESMethod = sbbEventXML.getInitialEventSelectorMethod();
// Secondly, do we need one now?
if (oldIESMethod != null && customIES == false) {
// Nuke the IES
sbbEventXML.setInitialEventSelectorMethod(null);
ClassUtil.removeMethodFromClass(abstractFile, oldIESMethod);
} else {
if (oldIESMethod == null && customIES == true) {
// Create the IES
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
}
}
// Deal with any change in the scoped name.
if (!oldScopedName.equals(scopedName)) {
sbbEventXML.setScopedName(scopedName);
// Rename the fire, receive and ies methods if they exist.
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName),
"on" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName),
"fire" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName) + "InitialEventSelect",
"on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
}
// Save the XML
xmlFile.setContents(sbbJarXML.getInputStreamFromXML(), true, true, monitor);
} catch (Exception e) {
MessageDialog.openError(new Shell(), "Error Modifying SBB", "An error occurred while modifying the service building block. It must be modified manually.");
e.printStackTrace();
System.err.println(e.toString() + ": " + e.getMessage());
return;
}
}
}
| public void run(IAction action) {
initialize();
if (dialog == null) {
MessageDialog.openError(new Shell(), "Error Modifying Service Building Block", getLastError());
return;
}
if (dialog.open() == Window.OK) {
try {
IProgressMonitor monitor = null;
HashMap newEvents[] = dialog.getSelectedEvents();
// foreach event in xml
// if not in newEvents
// delete event from xml and sbb abstract class
SbbEventXML oldEvents[] = sbb.getEvents();
for (int old = 0; old < oldEvents.length; old++) {
SbbEventXML oldEvent = oldEvents[old];
if (findEvent(oldEvent, newEvents) == null) {
// Nuke this event.
String scopedName = oldEvent.getScopedName();
sbb.removeEvent(oldEvent);
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "fire" + Utils.capitalize(scopedName));
ClassUtil.removeMethodFromClass(abstractFile, "on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
// foreach new event
// if getEvent(name, vendor, version) -- update
// else createEvent -- make receive, fire, ies methods
for (int i = 0; i < newEvents.length; i++) {
HashMap event = newEvents[i];
EventJarXML eventJarXML = (EventJarXML) event.get("XML");
EventXML eventXML = eventJarXML.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
SbbEventXML sbbEventXML = sbb.getEvent((String) event.get("Name"), (String) event.get("Vendor"), (String) event.get("Version"));
String scopedName = (String) event.get("Scoped Name");
String direction = (String) event.get("Direction");
boolean initialEvent = ((Boolean) event.get("Initial Event")).booleanValue();
String [] selectors = (String []) event.get("Initial Event Selectors");
if (sbbEventXML == null) {
sbbEventXML = sbb.addEvent(eventXML);
if(scopedName == null) {
scopedName = ((String) event.get("Name"));
scopedName = scopedName.substring(scopedName.lastIndexOf('.') + 1);
}
scopedName = scopedName.substring(0, 1).toUpperCase() + scopedName.substring(1);
sbbEventXML.setScopedName(scopedName);
sbbEventXML.setEventDirection(direction);
sbbEventXML.setInitialEvent(initialEvent);
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
} else {
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
if (direction.indexOf("Receive") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n");
if (direction.indexOf("Fire") != -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);");
} else {
// Modify the existing event.
String oldDirection = sbbEventXML.getEventDirection();
String oldScopedName = sbbEventXML.getScopedName();
// Deal with any changes in event direction
if (!oldDirection.equals(direction)) {
// Direction has changed.
if (direction.indexOf("Fire") == -1) {
// Nuke any fire method.
ClassUtil.removeMethodFromClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName));
} else {
// Create a fire method
if (oldDirection.indexOf("Fire") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic abstract void fire" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci, Address address);\n\n");
}
if (direction.indexOf("Receive") == -1) {
// nuke any receive method
ClassUtil.removeMethodFromClass(abstractFile,
"on" + Utils.capitalize(oldScopedName));
} else {
// Create the event handler
if (oldDirection.indexOf("Receive") == -1)
ClassUtil.addMethodToClass(abstractFile,
"\tpublic void on" + Utils.capitalize(scopedName) + "(" + eventXML.getEventClassName() + " event, ActivityContextInterface aci) {\n\n\t}\n\n");
}
sbbEventXML.setEventDirection(direction);
}
// Is this an initial event?
sbbEventXML.setInitialEvent(initialEvent);
// Remove old initial event selectors (N.B. not custom IES)
String oldSelectors[] = sbbEventXML.getInitialEventSelectors();
for (int j = 0; j < oldSelectors.length; j++) {
sbbEventXML.removeInitialEventSelector(oldSelectors[j]);
}
// Add new initial event selectors (N.B. not custom IES)
boolean customIES = false;
if (initialEvent) {
for (int j = 0; j < selectors.length; j++) {
if (selectors[j].equals("Custom")) {
customIES = true; // For next part.
continue;
}
sbbEventXML.addInitialEventSelector(selectors[j]);
}
}
// Deal with the IES -- first was there one originally
String oldIESMethod = sbbEventXML.getInitialEventSelectorMethod();
// Secondly, do we need one now?
if (oldIESMethod != null && customIES == false) {
// Nuke the IES
sbbEventXML.setInitialEventSelectorMethod(null);
ClassUtil.removeMethodFromClass(abstractFile, oldIESMethod);
} else {
if (oldIESMethod == null && customIES == true) {
// Create the IES
String methodName = "on" + Utils.capitalize(scopedName) + "InitialEventSelect";
String iesComment = "\t\t// TODO: Implement this method properly.\n" +
"\t\t// Please see Section 8.6.4 (Initial event selector method) of the\n" +
"\t\t// JAIN SLEE 1.1 Specification for more information.\n";
ClassUtil.addMethodToClass(abstractFile,
"\tpublic InitialEventSelector " + methodName + "(InitialEventSelector ies) {\n" + iesComment + "\t\treturn ies;\n\t}\n");
sbbEventXML.setInitialEventSelectorMethod(methodName);
}
}
// Deal with any change in the scoped name.
if (!oldScopedName.equals(scopedName)) {
sbbEventXML.setScopedName(scopedName);
sbbEventXML.setInitialEventSelectorMethod("on" + Utils.capitalize(scopedName) + "InitialEventSelect");
// Rename the fire, receive and ies methods if they exist.
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName),
"on" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"fire" + Utils.capitalize(oldScopedName),
"fire" + Utils.capitalize(scopedName));
ClassUtil.renameMethodInClass(abstractFile,
"on" + Utils.capitalize(oldScopedName) + "InitialEventSelect",
"on" + Utils.capitalize(scopedName) + "InitialEventSelect");
}
}
}
// Save the XML
xmlFile.setContents(sbbJarXML.getInputStreamFromXML(), true, true, monitor);
} catch (Exception e) {
MessageDialog.openError(new Shell(), "Error Modifying SBB", "An error occurred while modifying the service building block. It must be modified manually.");
e.printStackTrace();
System.err.println(e.toString() + ": " + e.getMessage());
return;
}
}
}
|
diff --git a/email/src/main/java/org/soluvas/email/impl/EmailManagerImpl.java b/email/src/main/java/org/soluvas/email/impl/EmailManagerImpl.java
index fb05127f..9aa8b805 100644
--- a/email/src/main/java/org/soluvas/email/impl/EmailManagerImpl.java
+++ b/email/src/main/java/org/soluvas/email/impl/EmailManagerImpl.java
@@ -1,203 +1,205 @@
package org.soluvas.email.impl;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.mail.Session;
import org.apache.commons.mail.Email;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.commons.AppManifest;
import org.soluvas.commons.WebAddress;
import org.soluvas.email.DefaultScope;
import org.soluvas.email.EmailCatalog;
import org.soluvas.email.EmailException;
import org.soluvas.email.EmailManager;
import org.soluvas.email.EmailPackage;
import org.soluvas.email.Layout;
import org.soluvas.email.LayoutType;
import org.soluvas.email.Page;
import org.soluvas.email.Sender;
import org.soluvas.email.util.EmailUtils;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Manager</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
/**
* @author rully
*
*/
@SuppressWarnings("serial")
public class EmailManagerImpl extends EObjectImpl implements EmailManager {
private static final Logger log = LoggerFactory.getLogger(EmailManagerImpl.class);
private final EmailCatalog emailCatalog;
private final String defaultLayoutNsPrefix;
private final String defaultLayoutName;
private final AppManifest appManifest;
private final WebAddress webAddress;
private final Session mailSession;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
protected EmailManagerImpl() {
throw new UnsupportedOperationException("Please use constructor arguments");
}
/**
* @param emailCatalog
* @param defaultLayoutNsPrefix
* @param defaultLayoutName
* @param smtpHost
* @param smtpPort
* @param smtpUser
* @param smtpPassword
* @param appManifest
* @param webAddress
*/
public EmailManagerImpl(EmailCatalog emailCatalog,
String defaultLayoutNsPrefix, String defaultLayoutName,
String smtpHost, int smtpPort, String smtpUser,
String smtpPassword, AppManifest appManifest, WebAddress webAddress) {
super();
this.emailCatalog = emailCatalog;
this.defaultLayoutNsPrefix = defaultLayoutNsPrefix;
this.defaultLayoutName = defaultLayoutName;
final Properties props = new Properties();
props.setProperty(Email.MAIL_HOST, smtpHost);
props.setProperty(Email.MAIL_PORT, Integer.toString(smtpPort));
props.setProperty(Email.MAIL_SMTP_USER, smtpUser);
props.setProperty(Email.MAIL_SMTP_PASSWORD, smtpPassword);
mailSession = Session.getInstance(props);
this.appManifest = appManifest;
this.webAddress = webAddress;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EmailPackage.Literals.EMAIL_MANAGER;
}
protected void injectDefaultScope(DefaultScope scope) {
scope.setAppManifest(appManifest);
scope.setWebAddress(webAddress);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
@Override
public <T extends Page> T createPage(Class<T> pageClass) {
final Layout layout = getDefaultLayout();
final T page = EmailUtils.createPage(pageClass, layout);
injectDefaultScope(page);
final Sender sender = createSender(page.getPageType().getSenderTypeName());
sender.expand();
page.setSender(sender);
page.setMailSession(mailSession);
return page;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
@Override
public Sender createSender(String qname) {
final String senderQName = Optional.fromNullable(qname).or("builtin:general");
final Matcher qnameMatcher = Pattern.compile("(.+):(.+)").matcher(senderQName);
final String senderNsPrefix = qnameMatcher.matches() ? qnameMatcher.group(1) : "builtin";
final String senderName = qnameMatcher.matches() ? qnameMatcher.group(2) : senderQName;
final Sender sender = EmailUtils.createSender(senderNsPrefix, senderName);
injectDefaultScope(sender);
return sender;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
@Override
public List<String> sendAll(Page page) {
final List<Email> emails = page.composeAll();
log.info("Sending {} emails using {}@{}:{}",
emails.size(), mailSession.getProperty(Email.MAIL_SMTP_USER),
mailSession.getProperty(Email.MAIL_HOST), mailSession.getProperty(Email.MAIL_PORT));
final List<String> results = ImmutableList.copyOf(Lists.transform(emails, new Function<Email, String>() {
@Override @Nullable
public String apply(@Nullable Email email) {
String result;
try {
Preconditions.checkNotNull(email.getMailSession(),
"Invalid mailSession for %s", email);
result = email.send();
log.info("Email sent from {} to {}: {} - {}",
email.getFromAddress(), email.getToAddresses(), result,
email.getSubject());
return result;
} catch (org.apache.commons.mail.EmailException e) {
- throw new EmailException("Cannot send email from " + email.getFromAddress() + " to " +
+ log.error("Cannot send email from " + email.getFromAddress() + " to " +
email.getToAddresses() + " subject: " + email.getSubject(), e);
+ // cannot be null because ImmutableList
+ return "";
}
}
}));
return results;
}
protected Layout getDefaultLayout() {
try {
final LayoutType layoutType = Iterables.find(emailCatalog.getLayoutTypes(), new Predicate<LayoutType>() {
@Override
public boolean apply(@Nullable LayoutType input) {
return Objects.equal(defaultLayoutNsPrefix, input.getNsPrefix())
&& Objects.equal(defaultLayoutName, input.getName());
}
});
final Layout layout = layoutType.create();
injectDefaultScope(layout);
return layout;
} catch (NoSuchElementException e) {
final List<String> layoutNames = Lists.transform(emailCatalog.getLayoutTypes(), new Function<LayoutType, String>() {
@Override @Nullable
public String apply(@Nullable LayoutType input) {
return input.getNsPrefix() + ":" + input.getName();
}
});
throw new EmailException(String.format("Cannot find layout %s:%s. %d available layouts are: %s.",
defaultLayoutNsPrefix, defaultLayoutName, layoutNames.size(), layoutNames), e);
}
}
} //EmailManagerImpl
| false | true | public List<String> sendAll(Page page) {
final List<Email> emails = page.composeAll();
log.info("Sending {} emails using {}@{}:{}",
emails.size(), mailSession.getProperty(Email.MAIL_SMTP_USER),
mailSession.getProperty(Email.MAIL_HOST), mailSession.getProperty(Email.MAIL_PORT));
final List<String> results = ImmutableList.copyOf(Lists.transform(emails, new Function<Email, String>() {
@Override @Nullable
public String apply(@Nullable Email email) {
String result;
try {
Preconditions.checkNotNull(email.getMailSession(),
"Invalid mailSession for %s", email);
result = email.send();
log.info("Email sent from {} to {}: {} - {}",
email.getFromAddress(), email.getToAddresses(), result,
email.getSubject());
return result;
} catch (org.apache.commons.mail.EmailException e) {
throw new EmailException("Cannot send email from " + email.getFromAddress() + " to " +
email.getToAddresses() + " subject: " + email.getSubject(), e);
}
}
}));
return results;
}
| public List<String> sendAll(Page page) {
final List<Email> emails = page.composeAll();
log.info("Sending {} emails using {}@{}:{}",
emails.size(), mailSession.getProperty(Email.MAIL_SMTP_USER),
mailSession.getProperty(Email.MAIL_HOST), mailSession.getProperty(Email.MAIL_PORT));
final List<String> results = ImmutableList.copyOf(Lists.transform(emails, new Function<Email, String>() {
@Override @Nullable
public String apply(@Nullable Email email) {
String result;
try {
Preconditions.checkNotNull(email.getMailSession(),
"Invalid mailSession for %s", email);
result = email.send();
log.info("Email sent from {} to {}: {} - {}",
email.getFromAddress(), email.getToAddresses(), result,
email.getSubject());
return result;
} catch (org.apache.commons.mail.EmailException e) {
log.error("Cannot send email from " + email.getFromAddress() + " to " +
email.getToAddresses() + " subject: " + email.getSubject(), e);
// cannot be null because ImmutableList
return "";
}
}
}));
return results;
}
|
diff --git a/deegree-services/deegree-services-wmts/src/main/java/org/deegree/services/wmts/controller/WmtsRequestDispatcher.java b/deegree-services/deegree-services-wmts/src/main/java/org/deegree/services/wmts/controller/WmtsRequestDispatcher.java
index 8b9d5d7b10..c0d7f2c16e 100644
--- a/deegree-services/deegree-services-wmts/src/main/java/org/deegree/services/wmts/controller/WmtsRequestDispatcher.java
+++ b/deegree-services/deegree-services-wmts/src/main/java/org/deegree/services/wmts/controller/WmtsRequestDispatcher.java
@@ -1,116 +1,117 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
Occam Labs UG (haftungsbeschränkt)
Godesberger Allee 139, 53175 Bonn
Germany
http://www.occamlabs.de/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wmts.controller;
import static org.deegree.commons.ows.exception.OWSException.NO_APPLICABLE_CODE;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.Map;
import javax.servlet.ServletException;
import org.deegree.commons.ows.exception.OWSException;
import org.deegree.commons.tom.ows.Version;
import org.deegree.protocol.wmts.WMTSConstants.WMTSRequestType;
import org.deegree.services.controller.utils.HttpResponseBuffer;
import org.deegree.services.jaxb.metadata.DeegreeServicesMetadataType;
import org.deegree.services.wmts.jaxb.DeegreeWMTS;
import org.deegree.workspace.ResourceLocation;
import org.deegree.workspace.Workspace;
import org.slf4j.Logger;
/**
* <code>RequestDispatcher</code>
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $
*/
class WmtsRequestDispatcher {
private static final Logger LOG = getLogger( WmtsRequestDispatcher.class );
private CapabilitiesHandler capabilitiesHandler;
private TileHandler tileHandler;
private FeatureInfoHandler featureInfoHandler;
WmtsRequestDispatcher( DeegreeWMTS controllerConf, DeegreeServicesMetadataType mainMetadataConf,
Workspace workspace, WmtsBuilder builder, String wmtsId, ResourceLocation<?> location ) {
featureInfoHandler = new FeatureInfoHandler( builder.getFeatureInfoFormatsConf(), location, workspace,
builder.getThemes() );
capabilitiesHandler = new CapabilitiesHandler( mainMetadataConf, workspace, builder.getMetadataUrlTemplate(),
wmtsId, builder.getThemes(), featureInfoHandler.getManager() );
tileHandler = new TileHandler( builder.getThemes() );
}
void handleRequest( WMTSRequestType req, HttpResponseBuffer response, Map<String, String> map, Version version )
throws OWSException, ServletException {
switch ( req ) {
case GetCapabilities:
try {
+ response.setContentType( "application/xml" );
capabilitiesHandler.handleGetCapabilities( map, response.getXMLWriter() );
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetFeatureInfo:
try {
featureInfoHandler.getFeatureInfo( map, response );
} catch ( OWSException e ) {
throw e;
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetTile:
tileHandler.getTile( map, response );
break;
}
}
}
| true | true | void handleRequest( WMTSRequestType req, HttpResponseBuffer response, Map<String, String> map, Version version )
throws OWSException, ServletException {
switch ( req ) {
case GetCapabilities:
try {
capabilitiesHandler.handleGetCapabilities( map, response.getXMLWriter() );
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetFeatureInfo:
try {
featureInfoHandler.getFeatureInfo( map, response );
} catch ( OWSException e ) {
throw e;
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetTile:
tileHandler.getTile( map, response );
break;
}
}
| void handleRequest( WMTSRequestType req, HttpResponseBuffer response, Map<String, String> map, Version version )
throws OWSException, ServletException {
switch ( req ) {
case GetCapabilities:
try {
response.setContentType( "application/xml" );
capabilitiesHandler.handleGetCapabilities( map, response.getXMLWriter() );
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetFeatureInfo:
try {
featureInfoHandler.getFeatureInfo( map, response );
} catch ( OWSException e ) {
throw e;
} catch ( Throwable e ) {
LOG.trace( "Stack trace:", e );
throw new OWSException( e.getMessage(), NO_APPLICABLE_CODE );
}
break;
case GetTile:
tileHandler.getTile( map, response );
break;
}
}
|
diff --git a/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java b/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
index 3bd62067..6955a67b 100644
--- a/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
+++ b/src/main/java/com/conventnunnery/plugins/mythicdrops/managers/DropManager.java
@@ -1,371 +1,371 @@
/*
* Copyright (c) 2013. ToppleTheNun
*
* 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.conventnunnery.plugins.mythicdrops.managers;
import com.conventnunnery.plugins.mythicdrops.MythicDrops;
import com.conventnunnery.plugins.mythicdrops.objects.CustomItem;
import com.conventnunnery.plugins.mythicdrops.objects.MythicEnchantment;
import com.conventnunnery.plugins.mythicdrops.objects.SocketGem;
import com.conventnunnery.plugins.mythicdrops.objects.SocketItem;
import com.conventnunnery.plugins.mythicdrops.objects.Tier;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentWrapper;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.Repairable;
import org.bukkit.material.MaterialData;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* A class that handles all of the plugin's drop creation.
*/
public class DropManager {
private final MythicDrops plugin;
private List<CustomItem> customItems;
/**
* Instantiates a new Drop API.
*
* @param plugin the plugin
*/
public DropManager(MythicDrops plugin) {
this.plugin = plugin;
customItems = new ArrayList<CustomItem>();
}
/**
* Construct a random ItemStack.
*
* @param reason the reason
* @return random ItemStack
*/
public ItemStack constructItemStack(GenerationReason reason) {
switch (reason) {
case MOB_SPAWN:
if (getPlugin().getPluginSettings().isAllowCustomToSpawn() &&
getPlugin().getPluginSettings().isOnlyCustomItems() ||
getPlugin().getRandom().nextDouble() <=
getPlugin().getPluginSettings().getPercentageCustomDrop() &&
!customItems.isEmpty()) {
return randomCustomItemWithChance().toItemStack();
}
if (getPlugin().getPluginSettings().isSocketGemsEnabled()
&& getPlugin().getRandom().nextDouble() < getPlugin()
.getPluginSettings().getSocketGemsChance()) {
MaterialData materialData = getPlugin().getSocketGemManager().getRandomSocketGemMaterial();
SocketGem socketGem = getPlugin().getSocketGemManager().getRandomSocketGemWithChance();
if (materialData != null && socketGem != null)
return new SocketItem(materialData, socketGem);
}
return constructItemStack(getPlugin().getTierManager().randomTierWithChance(), reason);
case COMMAND:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
case EXTERNAL:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
default:
return constructItemStack(getPlugin().getTierManager()
.randomTierWithChance(), reason);
}
}
/**
* Construct an ItemStack based on a Tier.
*
* @param tier Tier to base the ItemStack on
* @param reason reason to generate the ItemStack
* @return constructed ItemStack
*/
public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
if (me.getEnchantment() == null){
continue;
}
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
- getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel())));
+ getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1) - 1));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
if (te.getEnchantment() == null) {
continue;
}
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
/**
* Gets acceptable Enchantment level.
*
* @param ench the Enchantment
* @param level the level
* @return the acceptable Enchantment level
*/
public int getAcceptableEnchantmentLevel(Enchantment ench, int level) {
EnchantmentWrapper ew = new EnchantmentWrapper(ench.getId());
int i = level;
if (i > ew.getMaxLevel()) {
i = ew.getMaxLevel();
} else if (i < ew.getStartLevel()) {
i = ew.getStartLevel();
}
return i;
}
/**
* Gets custom items.
*
* @return the custom items
*/
public List<CustomItem> getCustomItems() {
return customItems;
}
/**
* Gets a list of Enchantments that can go on an ItemStack.
*
* @param ci ItemStack to check
* @return list of possible Enchantments
*/
public List<Enchantment> getEnchantStack(final ItemStack ci) {
List<Enchantment> set = new ArrayList<Enchantment>();
if (ci == null) {
return set;
}
boolean bln = getPlugin().getPluginSettings().isSafeEnchantsOnly();
for (Enchantment e : Enchantment.values()) {
if (bln) {
if (e.canEnchantItem(ci)) {
set.add(e);
}
} else {
set.add(e);
}
}
return set;
}
/**
* Gets plugin.
*
* @return the plugin
*/
public MythicDrops getPlugin() {
return plugin;
}
public void debugCustomItems() {
List<String> customItemNames = new ArrayList<String>();
for (CustomItem ci : customItems) {
customItemNames.add(ci.getName());
}
getPlugin().getDebug().debug(
"Loaded custom items: "
+ customItemNames.toString().replace("[", "")
.replace("]", ""));
}
/**
* Random custom item.
*
* @return the custom item
*/
@SuppressWarnings("unused")
public CustomItem randomCustomItem() {
return customItems.get(getPlugin().getRandom().nextInt(customItems.size()));
}
public CustomItem getCustomItemByName(String name) {
for (CustomItem i : customItems) {
if (name.equalsIgnoreCase(i.getName())) {
return i;
}
}
return null;
}
/**
* Random custom item with chance.
*
* @return the custom item
*/
public CustomItem randomCustomItemWithChance() {
CustomItem ci = null;
if (customItems == null || customItems.isEmpty())
return ci;
while (ci == null) {
for (CustomItem c : customItems) {
double d = plugin.getRandom().nextDouble();
if (d <= c.getChance()) {
ci = c;
break;
}
}
}
return ci;
}
/**
* Enum of GenerationReasons.
*/
public enum GenerationReason {
/**
* Use when spawning a mob
*/MOB_SPAWN, /**
* Use for commands
*/COMMAND, /**
* Use for anything else
*/EXTERNAL
}
}
| true | true | public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
if (me.getEnchantment() == null){
continue;
}
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel())));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
if (te.getEnchantment() == null) {
continue;
}
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
| public ItemStack constructItemStack(Tier tier, GenerationReason reason) {
ItemStack itemstack = null;
MaterialData matData = null;
int attempts = 0;
if (tier == null) {
return null;
}
while (matData == null && attempts < 10) {
matData = getPlugin().getItemManager().getMatDataFromTier(tier);
attempts++;
}
if (matData == null || matData.getItemTypeId() == 0
|| matData.getItemType() == Material.AIR)
return itemstack;
itemstack = matData.toItemStack(1);
if (itemstack == null) {
return itemstack;
}
if (reason != null && reason != GenerationReason.COMMAND) {
double min = Math.min(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double max = Math.max(tier.getMinimumDurability(), tier.getMaximumDurability()) *
itemstack.getType().getMaxDurability();
double minDuraPercent = itemstack.getType().getMaxDurability() -
Math.max(min, max) *
itemstack.getType().getMaxDurability();
double maxDuraPercent =
itemstack.getType().getMaxDurability() -
Math.min(min, max) *
itemstack.getType().getMaxDurability();
int minDura =
(int) minDuraPercent;
int maxDura = (int) maxDuraPercent;
short dura = (short) (getPlugin().getRandom()
.nextInt(
Math.abs(Math.max(minDura, maxDura) - Math.min(minDura, maxDura)) + 1) +
Math.min(minDura, maxDura));
itemstack.setDurability(dura);
}
for (MythicEnchantment me : tier.getBaseEnchantments()) {
if (me.getEnchantment() == null){
continue;
}
if (tier.isSafeBaseEnchantments() && me.getEnchantment().canEnchantItem(itemstack)) {
itemstack.addEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1) - 1));
} else if (!tier.isSafeBaseEnchantments()) {
itemstack.addUnsafeEnchantment(me.getEnchantment(), Math.abs(me.getMinimumLevel() +
getPlugin().getRandom().nextInt(me.getMaximumLevel() - me.getMinimumLevel() + 1)));
}
}
if (tier.getMaximumBonusEnchantments() > 0) {
int randEnchs = getPlugin().getRandom().nextInt(
Math.abs(tier.getMaximumBonusEnchantments() - tier.getMinimumBonusEnchantments() + 1)) +
tier.getMinimumBonusEnchantments();
for (int i = 0; i < randEnchs; i++) {
Set<MythicEnchantment> allowEnchs = tier.getBonusEnchantments();
List<Enchantment> stackEnchs = getEnchantStack(itemstack);
List<MythicEnchantment> actual = new ArrayList<MythicEnchantment>();
for (MythicEnchantment te : allowEnchs) {
if (te.getEnchantment() == null) {
continue;
}
if (stackEnchs.contains(te.getEnchantment())) {
actual.add(te);
}
}
if (actual.size() > 0) {
MythicEnchantment ench = actual.get(getPlugin().getRandom()
.nextInt(actual.size()));
int lev =
getPlugin().getRandom()
.nextInt(Math.abs(ench.getMaximumLevel() - ench.getMinimumLevel()) + 1) +
ench.getMinimumLevel();
if (getPlugin().getPluginSettings().isSafeEnchantsOnly()) {
if (!getPlugin().getPluginSettings().isAllowEnchantsPastNormalLevel()) {
itemstack.addEnchantment(
ench.getEnchantment(),
getAcceptableEnchantmentLevel(ench.getEnchantment(),
lev <= 0 ? 1 : Math.abs(lev)));
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
} else {
itemstack.addUnsafeEnchantment(ench.getEnchantment(), lev <= 0 ? 1 : Math.abs(lev));
}
}
}
}
if (matData.getItemType() == null) {
return itemstack;
}
ItemMeta im;
if (itemstack.hasItemMeta())
im = itemstack.getItemMeta();
else
im = Bukkit.getItemFactory().getItemMeta(matData.getItemType());
im.setDisplayName(getPlugin().getNameManager().randomFormattedName(
itemstack, tier));
List<String> toolTips = getPlugin().getPluginSettings()
.getAdvancedToolTipFormat();
List<String> tt = new ArrayList<String>();
for (String s : toolTips) {
tt.add(ChatColor.translateAlternateColorCodes(
'&',
s.replace("%itemtype%",
getPlugin().getNameManager().getItemTypeName(matData))
.replace("%tiername%",
tier.getDisplayColor() + tier.getDisplayName())
.replace(
"%basematerial%",
getPlugin().getNameManager()
.getMinecraftMaterialName(
itemstack.getType()))
.replace(
"%mythicmaterial%",
getPlugin().getNameManager()
.getMythicMaterialName(
itemstack.getData())).replace("%enchantment%",
tier.getDisplayColor() + getPlugin().getNameManager().getEnchantmentTypeName(itemstack) +
tier.getIdentificationColor())));
}
if (getPlugin().getPluginSettings().isSockettedItemsEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getSpawnWithSocketChance()) {
int amtTT = 0;
for (int i = 0;
i < getPlugin().getRandom()
.nextInt(Math.abs(tier.getMaximumSockets() - tier.getMinimumSockets()) + 1) +
tier.getMinimumSockets(); i++) {
tt.add(ChatColor.GOLD + "(Socket)");
amtTT++;
}
if (amtTT > 0) {
tt.add(ChatColor.GRAY + "Find a " + ChatColor.GOLD + "Socket Gem" + ChatColor.GRAY + " to fill a " +
ChatColor.GOLD + "(Socket)");
}
}
if (getPlugin().getPluginSettings().isRandomLoreEnabled() &&
getPlugin().getRandom().nextDouble() <= getPlugin().getPluginSettings().getRandomLoreChance() &&
!getPlugin().getNameManager().getBasicLore().isEmpty()) {
tt.addAll(getPlugin().getNameManager().randomLore());
}
im.setLore(tt);
if (im instanceof Repairable) {
Repairable r = (Repairable) im;
r.setRepairCost(1000);
itemstack.setItemMeta((ItemMeta) r);
} else {
itemstack.setItemMeta(im);
}
return itemstack;
}
|
diff --git a/org.ektorp/src/main/java/org/ektorp/ViewResult.java b/org.ektorp/src/main/java/org/ektorp/ViewResult.java
index 6b5b082..a5933a7 100644
--- a/org.ektorp/src/main/java/org/ektorp/ViewResult.java
+++ b/org.ektorp/src/main/java/org/ektorp/ViewResult.java
@@ -1,145 +1,145 @@
package org.ektorp;
import java.io.*;
import java.util.*;
import org.codehaus.jackson.*;
import org.codehaus.jackson.annotate.*;
import org.ektorp.util.*;
/**
*
* @author henrik lundgren
*
*/
public class ViewResult implements Iterable<ViewResult.Row>, Serializable {
private static final String OFFSET_FIELD_NAME = "offset";
private static final String TOTAL_ROWS_FIELD_NAME = "total_rows";
private static final long serialVersionUID = 4750290767933801714L;
private int totalRows = -1;
private int offset = -1;
private List<Row> rows;
public ViewResult(JsonNode resultNode) {
Assert.notNull(resultNode, "resultNode may not be null");
Assert.isTrue(resultNode.findPath("rows").isArray(), "result must contain 'rows' field of array type");
if (resultNode.get(TOTAL_ROWS_FIELD_NAME) != null) {
totalRows = resultNode.get(TOTAL_ROWS_FIELD_NAME).getIntValue();
}
if (resultNode.get(OFFSET_FIELD_NAME) != null) {
offset = resultNode.get(OFFSET_FIELD_NAME).getIntValue();
}
JsonNode rowsNode = resultNode.get("rows");
- rows = totalRows > -1 ? new ArrayList<ViewResult.Row>(totalRows) : new ArrayList<ViewResult.Row>();
+ rows = new ArrayList<ViewResult.Row>(rowsNode.size());
for (JsonNode n : rowsNode) {
rows.add(new Row(n));
}
}
public List<Row> getRows() {
return rows;
}
public int getSize() {
return rows.size();
}
/**
*
* @return -1 if result did not contain an offset field
*/
public int getOffset() {
return offset;
}
@JsonProperty
void setOffset(int offset) {
this.offset = offset;
}
/**
*
* @return -1 if result did not contain a total_rows field
*/
public int getTotalRows() {
return totalRows;
}
@JsonProperty(TOTAL_ROWS_FIELD_NAME)
void setTotalRows(int i) {
this.totalRows = i;
}
public Iterator<ViewResult.Row> iterator() {
return rows.iterator();
}
public boolean isEmpty() {
return rows.isEmpty();
}
public static class Row {
private static final String VALUE_FIELD_NAME = "value";
private static final String ID_FIELD_NAME = "id";
private static final String KEY_FIELD_NAME = "key";
private static final String DOC_FIELD_NAME = "doc";
private static final String ERROR_FIELD_NAME = "error";
private final JsonNode rowNode;
@JsonCreator
public Row(JsonNode rowNode) {
Assert.notNull(rowNode, "row node may not be null");
this.rowNode = rowNode;
if (getError() != null) {
throw new ViewResultException(getKeyAsNode(), getError());
}
}
public String getId() {
return rowNode.get(ID_FIELD_NAME).getTextValue();
}
public String getKey() {
return nodeAsString(getKeyAsNode());
}
public JsonNode getKeyAsNode() {
return rowNode.findPath(KEY_FIELD_NAME);
}
public String getValue() {
return nodeAsString(getValueAsNode());
}
public int getValueAsInt() {
return getValueAsNode().getValueAsInt(0);
}
public JsonNode getValueAsNode() {
return rowNode.findPath(VALUE_FIELD_NAME);
}
public String getDoc() {
return nodeAsString(rowNode.findValue(DOC_FIELD_NAME));
}
public JsonNode getDocAsNode() {
return rowNode.findPath(DOC_FIELD_NAME);
}
private String getError() {
return nodeAsString(rowNode.findValue(ERROR_FIELD_NAME));
}
private String nodeAsString(JsonNode node) {
if (isNull(node)) return null;
return node.isContainerNode() ? node.toString() : node.getValueAsText();
}
private boolean isNull(JsonNode node) {
return node == null || node.isNull() || node.isMissingNode();
}
}
}
| true | true | public ViewResult(JsonNode resultNode) {
Assert.notNull(resultNode, "resultNode may not be null");
Assert.isTrue(resultNode.findPath("rows").isArray(), "result must contain 'rows' field of array type");
if (resultNode.get(TOTAL_ROWS_FIELD_NAME) != null) {
totalRows = resultNode.get(TOTAL_ROWS_FIELD_NAME).getIntValue();
}
if (resultNode.get(OFFSET_FIELD_NAME) != null) {
offset = resultNode.get(OFFSET_FIELD_NAME).getIntValue();
}
JsonNode rowsNode = resultNode.get("rows");
rows = totalRows > -1 ? new ArrayList<ViewResult.Row>(totalRows) : new ArrayList<ViewResult.Row>();
for (JsonNode n : rowsNode) {
rows.add(new Row(n));
}
}
| public ViewResult(JsonNode resultNode) {
Assert.notNull(resultNode, "resultNode may not be null");
Assert.isTrue(resultNode.findPath("rows").isArray(), "result must contain 'rows' field of array type");
if (resultNode.get(TOTAL_ROWS_FIELD_NAME) != null) {
totalRows = resultNode.get(TOTAL_ROWS_FIELD_NAME).getIntValue();
}
if (resultNode.get(OFFSET_FIELD_NAME) != null) {
offset = resultNode.get(OFFSET_FIELD_NAME).getIntValue();
}
JsonNode rowsNode = resultNode.get("rows");
rows = new ArrayList<ViewResult.Row>(rowsNode.size());
for (JsonNode n : rowsNode) {
rows.add(new Row(n));
}
}
|
diff --git a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/m/IndexAction.java b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/m/IndexAction.java
index 11c3d5fad..aed986d0f 100644
--- a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/m/IndexAction.java
+++ b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/m/IndexAction.java
@@ -1,195 +1,195 @@
/**
* Copyright (c) 2011 Metropolitan Transportation Authority
*
* 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.onebusaway.nyc.webapp.actions.m;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.onebusaway.nyc.presentation.model.DistanceAway;
import org.onebusaway.nyc.presentation.model.Mode;
import org.onebusaway.nyc.presentation.model.RouteItem;
import org.onebusaway.nyc.presentation.model.StopItem;
import org.onebusaway.nyc.presentation.model.search.RouteSearchResult;
import org.onebusaway.nyc.presentation.model.search.SearchResult;
import org.onebusaway.nyc.presentation.model.search.StopSearchResult;
import org.onebusaway.nyc.presentation.service.NycSearchService;
import org.onebusaway.nyc.webapp.actions.OneBusAwayNYCActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
public class IndexAction extends OneBusAwayNYCActionSupport {
private static final String GA_ACCOUNT = "UA-XXXXXXXX-X";
private static final long serialVersionUID = 1L;
@Autowired
private NycSearchService searchService;
private String q;
private List<SearchResult> searchResults = new ArrayList<SearchResult>();
@Override
public String execute() throws Exception {
if (q != null)
searchResults = searchService.search(q, Mode.MOBILE_WEB);
return SUCCESS;
}
public List<SearchResult> getSearchResults() {
return searchResults;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
// Adapted from http://code.google.com/mobile/analytics/docs/web/#jsp
public String getGoogleAnalyticsTrackingUrl() {
try {
StringBuilder url = new StringBuilder();
url.append("/ga?");
url.append("utmac=").append(GA_ACCOUNT);
url.append("&utmn=").append(Integer.toString((int) (Math.random() * 0x7fffffff)));
// page path
url.append("&utmp=/m");
// referer
HttpServletRequest request = ServletActionContext.getRequest();
String referer = request.getHeader("referer");
if (referer == null || "".equals(referer)) {
referer = "-";
}
url.append("&utmr=").append(URLEncoder.encode(referer, "UTF-8"));
// event tracking
String label = getQ();
if(label == null) {
label = "";
}
String action = new String("Unknown");
if(searchResults != null && !searchResults.isEmpty()) {
SearchResult firstResult = searchResults.get(0);
if(firstResult.getType().equals("route")) {
action = "Route";
} else if(firstResult.getType().equals("stop")) {
if(searchResults.size() > 1) {
action = "Intersection";
} else {
action = "Stop";
}
}
} else {
if(getQueryIsEmpty()) {
action = "Home";
} else {
action = "No Results";
}
}
- url.append("&utme=5(Mobile Web*" + action + "*" + label + ")");
+ url.append("&utmt=event&utme=5(Mobile Web*" + action + "*" + label + ")");
// misc.
url.append("&guid=ON");
return url.toString().replace("&", "&");
} catch(Exception e) {
return null;
}
}
public boolean getQueryIsEmpty() {
if(q == null) {
return true;
} else {
return q.isEmpty();
}
}
public List<SearchResult>getToc() {
List<SearchResult> tocList = new ArrayList<SearchResult>();
for(SearchResult _result : searchResults) {
if(_result.getType().equals("route"))
tocList.add(_result);
else // if we find a non-route, there won't be any routes in the results.
break;
}
return tocList;
}
public String getCacheBreaker() {
return (int)Math.ceil((Math.random() * 100000)) + "";
}
public String getLastUpdateTime() {
Date lastUpdated = null;
for(SearchResult _result : searchResults) {
if(_result.getType().equals("route")) {
RouteSearchResult result = (RouteSearchResult)_result;
for(StopItem stop : result.getStopItems()) {
for(DistanceAway distanceAway : stop.getDistanceAways()) {
if(lastUpdated == null || distanceAway.getUpdateTimestamp().getTime() < lastUpdated.getTime()) {
lastUpdated = distanceAway.getUpdateTimestamp();
}
}
}
} else if(_result.getType().equals("stop")) {
StopSearchResult result = (StopSearchResult)_result;
for(RouteItem route : result.getRoutesAvailable()) {
for(DistanceAway distanceAway : route.getDistanceAways()) {
if(lastUpdated == null || distanceAway.getUpdateTimestamp().getTime() < lastUpdated.getTime()) {
lastUpdated = distanceAway.getUpdateTimestamp();
}
}
}
}
}
if(lastUpdated != null) {
return DateFormat.getTimeInstance().format(lastUpdated);
} else {
// no realtime data
return DateFormat.getTimeInstance().format(new Date());
}
}
public String getTitle() {
String title = this.q;
if(searchResults.size() == 1) {
SearchResult result = searchResults.get(0);
if(result != null) {
title = result.getName() + " (" + title + ")";
}
}
return title;
}
}
| true | true | public String getGoogleAnalyticsTrackingUrl() {
try {
StringBuilder url = new StringBuilder();
url.append("/ga?");
url.append("utmac=").append(GA_ACCOUNT);
url.append("&utmn=").append(Integer.toString((int) (Math.random() * 0x7fffffff)));
// page path
url.append("&utmp=/m");
// referer
HttpServletRequest request = ServletActionContext.getRequest();
String referer = request.getHeader("referer");
if (referer == null || "".equals(referer)) {
referer = "-";
}
url.append("&utmr=").append(URLEncoder.encode(referer, "UTF-8"));
// event tracking
String label = getQ();
if(label == null) {
label = "";
}
String action = new String("Unknown");
if(searchResults != null && !searchResults.isEmpty()) {
SearchResult firstResult = searchResults.get(0);
if(firstResult.getType().equals("route")) {
action = "Route";
} else if(firstResult.getType().equals("stop")) {
if(searchResults.size() > 1) {
action = "Intersection";
} else {
action = "Stop";
}
}
} else {
if(getQueryIsEmpty()) {
action = "Home";
} else {
action = "No Results";
}
}
url.append("&utme=5(Mobile Web*" + action + "*" + label + ")");
// misc.
url.append("&guid=ON");
return url.toString().replace("&", "&");
} catch(Exception e) {
return null;
}
}
| public String getGoogleAnalyticsTrackingUrl() {
try {
StringBuilder url = new StringBuilder();
url.append("/ga?");
url.append("utmac=").append(GA_ACCOUNT);
url.append("&utmn=").append(Integer.toString((int) (Math.random() * 0x7fffffff)));
// page path
url.append("&utmp=/m");
// referer
HttpServletRequest request = ServletActionContext.getRequest();
String referer = request.getHeader("referer");
if (referer == null || "".equals(referer)) {
referer = "-";
}
url.append("&utmr=").append(URLEncoder.encode(referer, "UTF-8"));
// event tracking
String label = getQ();
if(label == null) {
label = "";
}
String action = new String("Unknown");
if(searchResults != null && !searchResults.isEmpty()) {
SearchResult firstResult = searchResults.get(0);
if(firstResult.getType().equals("route")) {
action = "Route";
} else if(firstResult.getType().equals("stop")) {
if(searchResults.size() > 1) {
action = "Intersection";
} else {
action = "Stop";
}
}
} else {
if(getQueryIsEmpty()) {
action = "Home";
} else {
action = "No Results";
}
}
url.append("&utmt=event&utme=5(Mobile Web*" + action + "*" + label + ")");
// misc.
url.append("&guid=ON");
return url.toString().replace("&", "&");
} catch(Exception e) {
return null;
}
}
|
diff --git a/src/info/beverlyshill/samples/test/PagesControllerTest.java b/src/info/beverlyshill/samples/test/PagesControllerTest.java
index 7cd704a..77a956e 100755
--- a/src/info/beverlyshill/samples/test/PagesControllerTest.java
+++ b/src/info/beverlyshill/samples/test/PagesControllerTest.java
@@ -1,106 +1,106 @@
package info.beverlyshill.samples.test;
import info.beverlyshill.samples.controller.PagesController;
import info.beverlyshill.samples.model.Pages;
import info.beverlyshill.samples.model.PagesManager;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Test class for PagesController
*
* @author bhill
*/
public class PagesControllerTest extends TestCase {
private MockHttpServletRequest mockHttpServletRequest = null;
private PagesController pagesController = null;
private PagesManager pagesManager = new PagesManager();
private Pages page = null;
private String name = "Index";
private String desc = "description controller";
private boolean match = false;
private int pageId = 0;
private static Log log = LogFactory.getLog(PagesControllerTest.class);
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(PagesControllerTest.class);
}
/**
* Tests getting and setting the PagesManager on the
* PagesController
*/
public void testGetSetPagesManager() {
PagesController newPagesController = new PagesController();
PagesManager newPagesManager = new PagesManager();
newPagesController.setPagesManager(newPagesManager);
assertNotNull(newPagesController.getPagesManager());
}
/**
* Tests returning a list of Pages database objects
* from a ModelAndView request.
*/
public void testHandleRequest() throws Exception {
mockHttpServletRequest = new MockHttpServletRequest("GET",
"/index.html");
try {
pagesController = new PagesController();
pagesController.setPagesManager(pagesManager);
ModelAndView modelAndView = pagesController.handleRequest(
mockHttpServletRequest, null);
assertNotNull(modelAndView);
assertNotNull(modelAndView.getModel());
List pagesList = (List) modelAndView.getModel().get(
PagesController.MAP_KEY);
assertNotNull(pagesList);
for (int i = 0; i < pagesList.size(); i++) {
page = (Pages) pagesList.get(i);
if (desc.equals(page.getTextDesc())) {
match = true;
pageId = page.getPageId();
}
}
assertTrue(match == true);
System.out.println(page.getTextDesc() + " passed!");
} catch (Exception e) {
- log.error(e.getMessage());
+ log.error("An error occurred in testHandleRequest. The error is: " + e.getMessage());
throw e;
}
}
/**
* Create test Pages objects in database. This is called before each test.
*/
protected void setUp() throws Exception {
try {
Pages page = null;
page = new Pages();
page.setName(name);
page.setTextDesc(desc);
pagesManager.savePages(page);
} catch (Exception e) {
log.error(e.getMessage());
throw e;
}
}
/**
* Delete test Pages objects from the database. This is called after each
* test.
*/
protected void tearDown() throws Exception {
pagesManager.deletePage(pageId);
}
}
| true | true | public void testHandleRequest() throws Exception {
mockHttpServletRequest = new MockHttpServletRequest("GET",
"/index.html");
try {
pagesController = new PagesController();
pagesController.setPagesManager(pagesManager);
ModelAndView modelAndView = pagesController.handleRequest(
mockHttpServletRequest, null);
assertNotNull(modelAndView);
assertNotNull(modelAndView.getModel());
List pagesList = (List) modelAndView.getModel().get(
PagesController.MAP_KEY);
assertNotNull(pagesList);
for (int i = 0; i < pagesList.size(); i++) {
page = (Pages) pagesList.get(i);
if (desc.equals(page.getTextDesc())) {
match = true;
pageId = page.getPageId();
}
}
assertTrue(match == true);
System.out.println(page.getTextDesc() + " passed!");
} catch (Exception e) {
log.error(e.getMessage());
throw e;
}
}
| public void testHandleRequest() throws Exception {
mockHttpServletRequest = new MockHttpServletRequest("GET",
"/index.html");
try {
pagesController = new PagesController();
pagesController.setPagesManager(pagesManager);
ModelAndView modelAndView = pagesController.handleRequest(
mockHttpServletRequest, null);
assertNotNull(modelAndView);
assertNotNull(modelAndView.getModel());
List pagesList = (List) modelAndView.getModel().get(
PagesController.MAP_KEY);
assertNotNull(pagesList);
for (int i = 0; i < pagesList.size(); i++) {
page = (Pages) pagesList.get(i);
if (desc.equals(page.getTextDesc())) {
match = true;
pageId = page.getPageId();
}
}
assertTrue(match == true);
System.out.println(page.getTextDesc() + " passed!");
} catch (Exception e) {
log.error("An error occurred in testHandleRequest. The error is: " + e.getMessage());
throw e;
}
}
|
diff --git a/faia2/src/frsf/cidisi/faia/simulator/events/SimulatorEventNotifier.java b/faia2/src/frsf/cidisi/faia/simulator/events/SimulatorEventNotifier.java
index 7a76a39..cded47f 100644
--- a/faia2/src/frsf/cidisi/faia/simulator/events/SimulatorEventNotifier.java
+++ b/faia2/src/frsf/cidisi/faia/simulator/events/SimulatorEventNotifier.java
@@ -1,64 +1,64 @@
/*
* Copyright 2007-2009 Georgina Stegmayer, Milagros Gutiérrez, Jorge Roa
* y Milton Pividori.
*
* 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 frsf.cidisi.faia.simulator.events;
import java.util.Hashtable;
import java.util.Vector;
public class SimulatorEventNotifier {
private static Hashtable<EventType, Vector<EventHandler>> eventHandlers =
new Hashtable<EventType, Vector<EventHandler>>();
public static void runEventHandlers(EventType eventType, Object[] params) {
- if (!eventHandlers.contains(eventType)) {
+ if (!eventHandlers.containsKey(eventType)) {
return;
}
for (EventHandler eventHandler : eventHandlers.get(eventType)) {
eventHandler.runEventHandler(params);
}
}
public static void SubscribeEventHandler(EventType eventType, EventHandler eventHandler) {
if (!eventHandlers.contains(eventType)) {
eventHandlers.put(eventType, new Vector<EventHandler>());
}
Vector<EventHandler> eventHandlerList =
eventHandlers.get(eventType);
eventHandlerList.add(eventHandler);
}
public static void UnsubscribeEventHandler(EventType eventType, EventHandler eventHandler) {
if (!eventHandlers.contains(eventType)) {
return;
}
Vector<EventHandler> eventHandlerList =
eventHandlers.get(eventType);
eventHandlerList.remove(eventHandler);
}
public static void ClearEventHandlers() {
eventHandlers.clear();
}
}
| true | true | public static void runEventHandlers(EventType eventType, Object[] params) {
if (!eventHandlers.contains(eventType)) {
return;
}
for (EventHandler eventHandler : eventHandlers.get(eventType)) {
eventHandler.runEventHandler(params);
}
}
| public static void runEventHandlers(EventType eventType, Object[] params) {
if (!eventHandlers.containsKey(eventType)) {
return;
}
for (EventHandler eventHandler : eventHandlers.get(eventType)) {
eventHandler.runEventHandler(params);
}
}
|
diff --git a/mmstudio/src/org/micromanager/acquisition/CoreAcquisitionWrapperEngine.java b/mmstudio/src/org/micromanager/acquisition/CoreAcquisitionWrapperEngine.java
index 7e2d6b224..700821edd 100644
--- a/mmstudio/src/org/micromanager/acquisition/CoreAcquisitionWrapperEngine.java
+++ b/mmstudio/src/org/micromanager/acquisition/CoreAcquisitionWrapperEngine.java
@@ -1,707 +1,707 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.micromanager.acquisition;
import java.awt.Color;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import mmcorej.AcquisitionSettings;
import mmcorej.CMMCore;
import mmcorej.Channel;
import mmcorej.ChannelVector;
import mmcorej.Configuration;
import mmcorej.DoubleVector;
import mmcorej.MultiAxisPosition;
import mmcorej.MultiAxisPositionVector;
import mmcorej.PropertySetting;
import mmcorej.StrVector;
import org.micromanager.MMStudioMainFrame;
import org.micromanager.api.AcquisitionEngine;
import org.micromanager.api.DeviceControlGUI;
import org.micromanager.metadata.MMAcqDataException;
import org.micromanager.metadata.WellAcquisitionData;
import org.micromanager.navigation.MultiStagePosition;
import org.micromanager.navigation.PositionList;
import org.micromanager.navigation.StagePosition;
import org.micromanager.utils.AutofocusManager;
import org.micromanager.utils.ChannelSpec;
import org.micromanager.utils.ContrastSettings;
import org.micromanager.utils.MMException;
import org.micromanager.utils.NumberUtils;
import org.micromanager.utils.PositionMode;
import org.micromanager.utils.ReportingUtils;
import org.micromanager.utils.SliceMode;
/**
*
* @author arthur
*/
public class CoreAcquisitionWrapperEngine implements AcquisitionEngine {
private CMMCore core_;
private MMStudioMainFrame gui_;
private PositionList posList_ = new PositionList();
private String zstage_;
private boolean updateLiveWin_;
private double sliceZStepUm_;
private double sliceZBottomUm_;
private double sliceZTopUm_;
private boolean useSlices_;
private boolean useFrames_;
private boolean useChannels_;
private boolean keepShutterOpenForStack_;
private boolean keepShutterOpenForChannels_;
private boolean useMultiPosition_;
private ArrayList<ChannelSpec> channels_ = new ArrayList<ChannelSpec>();
private String rootName_;
private String dirName_;
private DoubleVector timeSeries_;
private int numFrames_;
private double interval_;
private AcquisitionDisplay display_;
private double minZStepUm_;
private String comment_;
private boolean saveFiles_;
private int displayMode_;
private int sliceMode_;
private int positionMode_;
private boolean useAutoFocus_;
private int afSkipInterval_;
private boolean useSingleFrame_;
private boolean useSingleWindow_;
private boolean isPaused_;
private String zStage_;
private String cameraConfig_;
private Preferences prefs_;
private ArrayList<ChannelSpec> requestedChannels_ = new ArrayList<ChannelSpec>();
public void acquire() throws MMException, MMAcqDataException {
try {
core_.setCircularBufferMemoryFootprint(32);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
AcquisitionSettings acquisitionSettings = generateAcquisitionSettings();
try {
core_.runAcquisitionEngineTest(acquisitionSettings);
} catch (Exception ex) {
ReportingUtils.showError(ex);
}
display_ = new AcquisitionDisplay(gui_, core_, acquisitionSettings, channels_, saveFiles_);
display_.start();
}
private AcquisitionSettings generateAcquisitionSettings() {
AcquisitionSettings acquisitionSettings = new AcquisitionSettings();
// Frames
if (useFrames_) {
DoubleVector timeSeries = new DoubleVector();
for (int i = 0; i < numFrames_; ++i) {
timeSeries.add(interval_);
}
acquisitionSettings.setTimeSeries(timeSeries);
}
// Slices
if (useSlices_) {
DoubleVector slices = new DoubleVector();
for (double z = sliceZBottomUm_; z<= sliceZTopUm_; z+=sliceZStepUm_) {
slices.add(z);
}
acquisitionSettings.setZStack(slices);
}
// Channels
if (useChannels_) {
ChannelVector channelVector = new ChannelVector();
for (ChannelSpec guiChan:channels_) {
Channel coreChan = new Channel(guiChan.name_, guiChan.config_,
guiChan.exposure_, guiChan.zOffset_,
guiChan.doZStack_, guiChan.skipFactorFrame_);
channelVector.add(coreChan);
}
acquisitionSettings.setChannelList(channelVector);
}
// Positions
StagePosition stagePos;
MultiAxisPositionVector corePosVector = new MultiAxisPositionVector();
if (useMultiPosition_) {
for(MultiStagePosition guiPos:posList_.getPositions()) {
MultiAxisPosition corePos = new MultiAxisPosition();
corePos.setName(guiPos.getLabel());
for(int i=0;i<guiPos.size();++i) {
stagePos = guiPos.get(i);
if (stagePos.numAxes == 2)
corePos.AddDoubleAxisPosition(stagePos.stageName, stagePos.x, stagePos.y);
else if (stagePos.numAxes == 1)
corePos.AddSingleAxisPosition(stagePos.stageName, stagePos.z);
}
corePosVector.add(corePos);
}
acquisitionSettings.setPositionList(corePosVector);
}
acquisitionSettings.setPositionsFirst(positionMode_ == PositionMode.TIME_LAPSE);
acquisitionSettings.setChannelsFirst(sliceMode_ == SliceMode.CHANNELS_FIRST);
acquisitionSettings.setUseAutofocus(useAutoFocus_);
acquisitionSettings.setAutofocusSkipFrames(afSkipInterval_);
acquisitionSettings.setKeepShutterOpenChannels(keepShutterOpenForChannels_);
acquisitionSettings.setKeepShutterOpenSlices(keepShutterOpenForStack_);
acquisitionSettings.setSaveImages(saveFiles_);
acquisitionSettings.setRoot(rootName_);
acquisitionSettings.setPrefix(dirName_);
return acquisitionSettings;
}
//////////////////// Actions ///////////////////////////////////////////
public boolean acquireWellScan(WellAcquisitionData wad) throws MMException, MMAcqDataException {
throw new UnsupportedOperationException("Not supported yet.");
}
public void stop(boolean interrupted) {
try {
core_.stopAcquisitionEngine();
} catch (Exception ex) {
ReportingUtils.showError("Acquisition engine stop request failed");
}
}
public void abortRequest() {
stop(true);
}
public void shutdown() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setPause(boolean state) {
throw new UnsupportedOperationException("Not supported yet.");
}
//// State Queries /////////////////////////////////////////////////////
public boolean isAcquisitionRunning() {
try {
return !core_.acquisitionIsFinished();
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
}
public boolean isMultiFieldRunning() {
return false;
//throw new UnsupportedOperationException("Not supported yet.");
}
//////////////////// Setters and Getters ///////////////////////////////
public void setCore(CMMCore core_, AutofocusManager afMgr) {
this.core_ = core_;
}
public void setPositionList(PositionList posList) {
posList_ = posList;
}
public void setParentGUI(DeviceControlGUI parent) {
gui_ = (MMStudioMainFrame) parent;
}
public void setZStageDevice(String stageLabel_) {
zstage_ = stageLabel_;
}
public void setUpdateLiveWindow(boolean b) {
updateLiveWin_ = b;
}
public void setFinished() {
throw new UnsupportedOperationException("Not supported yet.");
}
public int getCurrentFrameCount() {
return 0;
}
public double getFrameIntervalMs() {
return interval_;
}
public double getSliceZStepUm() {
return sliceZStepUm_;
}
public double getSliceZBottomUm() {
return sliceZBottomUm_;
}
public void setChannel(int row, ChannelSpec channel) {
channels_.set(row, channel);
}
/**
* Get first available config group
*/
public String getFirstConfigGroup() {
if (core_ == null) {
return new String("");
}
String[] groups = getAvailableGroups();
if (groups == null || groups.length < 1) {
return new String("");
}
return getAvailableGroups()[0];
}
/**
* Find out which channels are currently available for the selected channel group.
* @return - list of channel (preset) names
*/
public String[] getChannelConfigs() {
if (core_ == null) {
return new String[0];
}
return core_.getAvailableConfigs(core_.getChannelGroup()).toArray();
}
public int getNumFrames() {
return numFrames_;
}
public String getChannelGroup() {
return core_.getChannelGroup();
}
public boolean setChannelGroup(String group) {
if (groupIsEligibleChannel(group)) {
try {
core_.setChannelGroup(group);
} catch (Exception e) {
try {
core_.setChannelGroup("");
} catch (Exception ex) {
ReportingUtils.showError(e);
}
return false;
}
return true;
} else {
return false;
}
}
/**
* Resets the engine.
*/
public void clear() {
if (channels_ != null)
channels_.clear();
numFrames_ = 0;
}
public void setFrames(int numFrames, double interval) {
numFrames_ = numFrames;
interval_ = interval;
}
public double getMinZStepUm() {
return minZStepUm_;
}
public void setSlices(double bottom, double top, double step, boolean b) {
sliceZBottomUm_ = bottom;
sliceZTopUm_ = top;
sliceZStepUm_ = step;
useSlices_ = b;
}
public boolean isFramesSettingEnabled() {
return useFrames_;
}
public void enableFramesSetting(boolean enable) {
useFrames_ = enable;
}
public boolean isChannelsSettingEnabled() {
return useChannels_;
}
public void enableChannelsSetting(boolean enable) {
useChannels_ = enable;
}
public boolean isZSliceSettingEnabled() {
return useSlices_;
}
public double getZTopUm() {
return sliceZTopUm_;
}
public void keepShutterOpenForStack(boolean open) {
keepShutterOpenForStack_ = open;
}
public boolean isShutterOpenForStack() {
return keepShutterOpenForStack_;
}
public void keepShutterOpenForChannels(boolean open) {
keepShutterOpenForChannels_ = open;
}
public boolean isShutterOpenForChannels() {
return keepShutterOpenForChannels_;
}
public void enableZSliceSetting(boolean boolean1) {
useSlices_ = boolean1;
}
public void enableMultiPosition(boolean selected) {
useMultiPosition_ = selected;
}
public boolean isMultiPositionEnabled() {
return useMultiPosition_;
}
public ArrayList<ChannelSpec> getChannels() {
return channels_;
}
public void setChannels(ArrayList<ChannelSpec> channels) {
channels_ = channels;
}
public String getRootName() {
return rootName_;
}
public void setRootName(String absolutePath) {
rootName_ = absolutePath;
}
public void setCameraConfig(String cfg) {
cameraConfig_ = cfg;
}
public void setDirName(String text) {
dirName_ = text;
}
public void setComment(String text) {
comment_ = text;
}
/**
* Add new channel if the current state of the hardware permits.
*
* @param config - configuration name
* @param exp
* @param doZOffst
* @param zOffset
* @param c8
* @param c16
* @param c
* @return - true if successful
*/
public boolean addChannel(String config, double exp, Boolean doZStack, double zOffset, ContrastSettings c8, ContrastSettings c16, int skip, Color c) {
if (isConfigAvailable(config)) {
ChannelSpec channel = new ChannelSpec();
channel.config_ = config;
channel.exposure_ = exp;
channel.doZStack_ = doZStack;
channel.zOffset_ = zOffset;
channel.contrast8_ = c8;
channel.contrast16_ = c16;
channel.color_ = c;
channel.skipFactorFrame_ = skip;
requestedChannels_.add(channel);
return true;
} else {
return false;
}
}
/**
* Add new channel if the current state of the hardware permits.
*
* @param config - configuration name
* @param exp
* @param zOffset
* @param c8
* @param c16
* @param c
* @return - true if successful
* @deprecated
*/
public boolean addChannel(String config, double exp, double zOffset, ContrastSettings c8, ContrastSettings c16, int skip, Color c) {
return addChannel(config, exp, true, zOffset, c8, c16, skip, c);
}
public void setSaveFiles(boolean selected) {
saveFiles_ = selected;
}
public boolean getSaveFiles() {
return saveFiles_;
}
public void setDisplayMode(int mode) {
displayMode_ = mode;
}
public int getSliceMode() {
return sliceMode_;
}
public int getDisplayMode() {
return displayMode_;
}
public void setSliceMode(int mode) {
sliceMode_ = mode;
}
public int getPositionMode() {
return positionMode_;
}
public void setPositionMode(int mode) {
positionMode_ = mode;
}
public void enableAutoFocus(boolean enabled) {
useAutoFocus_ = enabled;
}
public boolean isAutoFocusEnabled() {
return useAutoFocus_;
}
public int getAfSkipInterval() {
return afSkipInterval_;
}
public void setAfSkipInterval(int interval) {
afSkipInterval_ = interval;
}
public void setParameterPreferences(Preferences prefs) {
prefs_ = prefs;
}
public void setSingleFrame(boolean selected) {
useSingleFrame_ = selected;
}
public void setSingleWindow(boolean selected) {
useSingleWindow_ = selected;
}
public String installAutofocusPlugin(String className) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getVerboseSummary() {
int numFrames = numFrames_;
if (!useFrames_) {
numFrames = 1;
}
- int numSlices = useSlices_ ? (int) ((sliceZTopUm_-sliceZBottomUm_)/sliceZStepUm_) : 1;
+ int numSlices = useSlices_ ? (int) (1 + (sliceZTopUm_-sliceZBottomUm_)/sliceZStepUm_) : 1;
if (!useSlices_) {
numSlices = 1;
}
int numPositions = Math.max(1, posList_.getNumberOfPositions());
if (!useMultiPosition_) {
numPositions = 1;
}
int numChannels = channels_.size();
if (!useChannels_) {
numChannels = 1;
}
int totalImages = numFrames * numSlices * numChannels * numPositions;
double totalDurationSec = interval_ * numFrames / 1000.0;
int hrs = (int) (totalDurationSec / 3600);
double remainSec = totalDurationSec - hrs * 3600;
int mins = (int) (remainSec / 60);
remainSec = remainSec - mins * 60;
Runtime rt = Runtime.getRuntime();
rt.gc();
String txt;
txt =
"Number of time points: " + numFrames
+ "\nNumber of positions: " + numPositions
+ "\nNumber of slices: " + numSlices
+ "\nNumber of channels: " + numChannels
+ "\nTotal images: " + totalImages
+ "\nDuration: " + hrs + "h " + mins + "m " + NumberUtils.doubleToDisplayString(remainSec) + "s";
String order = "\nOrder: ";
String ptSetting = null;
if (useMultiPosition_ && useFrames_) {
if (positionMode_ == PositionMode.TIME_LAPSE) {
ptSetting = "Position, Time";
} else if (positionMode_ == PositionMode.MULTI_FIELD) {
ptSetting = "Time, Position";
}
} else if (useMultiPosition_ && !useFrames_) {
ptSetting = "Position";
} else if (!useMultiPosition_ && useFrames_) {
ptSetting = "Time";
}
String csSetting = null;
if (useSlices_ && useChannels_) {
if (sliceMode_ == SliceMode.CHANNELS_FIRST) {
csSetting = "Channel, Slice";
} else {
csSetting = "Slice, Channel";
}
} else if (useSlices_ && !useChannels_) {
csSetting = "Slice";
} else if (!useSlices_ && useChannels_) {
csSetting = "Channel";
}
if (ptSetting == null && csSetting == null) {
order = "";
} else if (ptSetting != null && csSetting == null) {
order += ptSetting;
} else if (ptSetting == null && csSetting != null) {
order += csSetting;
} else if (ptSetting != null && csSetting != null) {
order += csSetting + ", " + ptSetting;
}
return txt + order;
}
/**
* Find out if the configuration is compatible with the current group.
* This method should be used to verify if the acquisition protocol is consistent
* with the current settings.
*/
public boolean isConfigAvailable(String config) {
StrVector vcfgs = core_.getAvailableConfigs(core_.getChannelGroup());
for (int i = 0; i < vcfgs.size(); i++) {
if (config.compareTo(vcfgs.get(i)) == 0) {
return true;
}
}
return false;
}
public String[] getCameraConfigs() {
if (core_ == null) {
return new String[0];
}
return core_.getAvailableConfigs(cameraGroup_).toArray();
}
public String[] getAvailableGroups() {
StrVector groups;
try {
groups = core_.getAllowedPropertyValues("Core", "ChannelGroup");
} catch (Exception ex) {
ReportingUtils.logError(ex);
return new String[0];
}
ArrayList<String> strGroups = new ArrayList<String>();
for (String group:groups) {
if (groupIsEligibleChannel(group)) {
strGroups.add(group);
}
}
return strGroups.toArray(new String[0]);
}
public double getCurrentZPos() {
if (isFocusStageAvailable()) {
double z = 0.0;
try {
//core_.waitForDevice(zstage_);
// NS: make sure we work with the current Focus device
z = core_.getPosition(core_.getFocusDevice());
} catch (Exception e) {
// TODO Auto-generated catch block
ReportingUtils.showError(e);
}
return z;
}
return 0;
}
public boolean isPaused() {
return isPaused_;
}
public void restoreSystem() {
throw new UnsupportedOperationException("Not supported yet.");
}
protected boolean isFocusStageAvailable() {
if (zstage_ != null && zstage_.length() > 0) {
return true;
} else {
return false;
}
}
private boolean groupIsEligibleChannel(String group) {
StrVector cfgs = core_.getAvailableConfigs(group);
if (cfgs.size() == 1) {
Configuration presetData;
try {
presetData = core_.getConfigData(group, cfgs.get(0));
if (presetData.size() == 1) {
PropertySetting setting = presetData.getSetting(0);
String devLabel = setting.getDeviceLabel();
String propName = setting.getPropertyName();
if (core_.hasPropertyLimits(devLabel, propName)) {
return false;
}
}
} catch (Exception ex) {
ReportingUtils.logError(ex);
return false;
}
}
return true;
}
}
| true | true | public String getVerboseSummary() {
int numFrames = numFrames_;
if (!useFrames_) {
numFrames = 1;
}
int numSlices = useSlices_ ? (int) ((sliceZTopUm_-sliceZBottomUm_)/sliceZStepUm_) : 1;
if (!useSlices_) {
numSlices = 1;
}
int numPositions = Math.max(1, posList_.getNumberOfPositions());
if (!useMultiPosition_) {
numPositions = 1;
}
int numChannels = channels_.size();
if (!useChannels_) {
numChannels = 1;
}
int totalImages = numFrames * numSlices * numChannels * numPositions;
double totalDurationSec = interval_ * numFrames / 1000.0;
int hrs = (int) (totalDurationSec / 3600);
double remainSec = totalDurationSec - hrs * 3600;
int mins = (int) (remainSec / 60);
remainSec = remainSec - mins * 60;
Runtime rt = Runtime.getRuntime();
rt.gc();
String txt;
txt =
"Number of time points: " + numFrames
+ "\nNumber of positions: " + numPositions
+ "\nNumber of slices: " + numSlices
+ "\nNumber of channels: " + numChannels
+ "\nTotal images: " + totalImages
+ "\nDuration: " + hrs + "h " + mins + "m " + NumberUtils.doubleToDisplayString(remainSec) + "s";
String order = "\nOrder: ";
String ptSetting = null;
if (useMultiPosition_ && useFrames_) {
if (positionMode_ == PositionMode.TIME_LAPSE) {
ptSetting = "Position, Time";
} else if (positionMode_ == PositionMode.MULTI_FIELD) {
ptSetting = "Time, Position";
}
} else if (useMultiPosition_ && !useFrames_) {
ptSetting = "Position";
} else if (!useMultiPosition_ && useFrames_) {
ptSetting = "Time";
}
String csSetting = null;
if (useSlices_ && useChannels_) {
if (sliceMode_ == SliceMode.CHANNELS_FIRST) {
csSetting = "Channel, Slice";
} else {
csSetting = "Slice, Channel";
}
} else if (useSlices_ && !useChannels_) {
csSetting = "Slice";
} else if (!useSlices_ && useChannels_) {
csSetting = "Channel";
}
if (ptSetting == null && csSetting == null) {
order = "";
} else if (ptSetting != null && csSetting == null) {
order += ptSetting;
} else if (ptSetting == null && csSetting != null) {
order += csSetting;
} else if (ptSetting != null && csSetting != null) {
order += csSetting + ", " + ptSetting;
}
return txt + order;
}
| public String getVerboseSummary() {
int numFrames = numFrames_;
if (!useFrames_) {
numFrames = 1;
}
int numSlices = useSlices_ ? (int) (1 + (sliceZTopUm_-sliceZBottomUm_)/sliceZStepUm_) : 1;
if (!useSlices_) {
numSlices = 1;
}
int numPositions = Math.max(1, posList_.getNumberOfPositions());
if (!useMultiPosition_) {
numPositions = 1;
}
int numChannels = channels_.size();
if (!useChannels_) {
numChannels = 1;
}
int totalImages = numFrames * numSlices * numChannels * numPositions;
double totalDurationSec = interval_ * numFrames / 1000.0;
int hrs = (int) (totalDurationSec / 3600);
double remainSec = totalDurationSec - hrs * 3600;
int mins = (int) (remainSec / 60);
remainSec = remainSec - mins * 60;
Runtime rt = Runtime.getRuntime();
rt.gc();
String txt;
txt =
"Number of time points: " + numFrames
+ "\nNumber of positions: " + numPositions
+ "\nNumber of slices: " + numSlices
+ "\nNumber of channels: " + numChannels
+ "\nTotal images: " + totalImages
+ "\nDuration: " + hrs + "h " + mins + "m " + NumberUtils.doubleToDisplayString(remainSec) + "s";
String order = "\nOrder: ";
String ptSetting = null;
if (useMultiPosition_ && useFrames_) {
if (positionMode_ == PositionMode.TIME_LAPSE) {
ptSetting = "Position, Time";
} else if (positionMode_ == PositionMode.MULTI_FIELD) {
ptSetting = "Time, Position";
}
} else if (useMultiPosition_ && !useFrames_) {
ptSetting = "Position";
} else if (!useMultiPosition_ && useFrames_) {
ptSetting = "Time";
}
String csSetting = null;
if (useSlices_ && useChannels_) {
if (sliceMode_ == SliceMode.CHANNELS_FIRST) {
csSetting = "Channel, Slice";
} else {
csSetting = "Slice, Channel";
}
} else if (useSlices_ && !useChannels_) {
csSetting = "Slice";
} else if (!useSlices_ && useChannels_) {
csSetting = "Channel";
}
if (ptSetting == null && csSetting == null) {
order = "";
} else if (ptSetting != null && csSetting == null) {
order += ptSetting;
} else if (ptSetting == null && csSetting != null) {
order += csSetting;
} else if (ptSetting != null && csSetting != null) {
order += csSetting + ", " + ptSetting;
}
return txt + order;
}
|
diff --git a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
index d95bf84a1..97db547b1 100644
--- a/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
+++ b/bundles/org.eclipse.equinox.p2.ui/src/org/eclipse/equinox/internal/provisional/p2/ui/operations/ProvisioningUtil.java
@@ -1,396 +1,398 @@
/*******************************************************************************
* Copyright (c) 2007, 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.internal.provisional.p2.ui.operations;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.p2.ui.*;
import org.eclipse.equinox.internal.p2.ui.model.IIUElement;
import org.eclipse.equinox.internal.provisional.configurator.Configurator;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepository;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.internal.provisional.p2.director.*;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.repository.IRepository;
import org.eclipse.equinox.internal.provisional.p2.repository.RepositoryEvent;
import org.eclipse.equinox.internal.provisional.p2.ui.ProvisioningOperationRunner;
import org.eclipse.osgi.util.NLS;
/**
* Utility methods for clients using the provisioning UI
*
* @since 3.4
*/
public class ProvisioningUtil {
public static void addMetadataRepository(URI location, boolean notify) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.addRepository(location);
if (notify) {
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.ADDED));
}
}
}
public static String getMetadataRepositoryProperty(URI location, String key) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
return manager.getRepositoryProperty(location, key);
}
public static void setMetadataRepositoryProperty(URI location, String key, String value) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.setRepositoryProperty(location, key, value);
}
public static boolean getMetadataRepositoryEnablement(URI location) {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
return false;
return manager.isEnabled(location);
}
public static boolean getArtifactRepositoryEnablement(URI location) {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
return false;
return manager.isEnabled(location);
}
public static IMetadataRepository loadMetadataRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
IMetadataRepository repo = manager.loadRepository(location, monitor);
// If there is no user nickname assigned to this repo but there is a provider name, then set the nickname.
// This will keep the name in the manager even when the repo is not loaded
String name = getMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME);
if (name == null) {
name = getMetadataRepositoryProperty(location, IRepository.PROP_NAME);
if (name != null)
setMetadataRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
}
return repo;
}
public static IStatus validateMetadataRepositoryLocation(URI location, IProgressMonitor monitor) {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null)
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
return manager.validateRepositoryLocation(location, monitor);
}
public static void removeMetadataRepository(URI location) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.removeRepository(location);
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_METADATA, RepositoryEvent.REMOVED));
}
}
public static void addArtifactRepository(URI location, boolean notify) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.addRepository(location);
if (notify) {
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.ADDED));
}
}
}
public static String getArtifactRepositoryProperty(URI location, String key) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getRepositoryProperty(location, key);
}
public static void setArtifactRepositoryProperty(URI location, String key, String value) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
manager.setRepositoryProperty(location, key, value);
}
public static IArtifactRepository loadArtifactRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null)
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
IArtifactRepository repo = manager.loadRepository(location, monitor);
if (repo == null) {
throw new ProvisionException(NLS.bind(ProvUIMessages.ProvisioningUtil_LoadRepositoryFailure, location));
}
// If there is no user nickname assigned to this repo but there is a provider name, then set the nickname.
// This will keep the name in the manager even when the repo is not loaded
String name = getArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME);
if (name == null) {
name = getArtifactRepositoryProperty(location, IRepository.PROP_NAME);
if (name != null)
setArtifactRepositoryProperty(location, IRepository.PROP_NICKNAME, name);
}
return repo;
}
public static void removeArtifactRepository(URI location) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
manager.removeRepository(location);
IProvisioningEventBus bus = ProvUIActivator.getDefault().getProvisioningEventBus();
if (bus != null) {
bus.publishEvent(new UIRepositoryEvent(location, IRepository.TYPE_ARTIFACT, RepositoryEvent.REMOVED));
}
}
public static IProfile addProfile(String profileId, Map properties, IProgressMonitor monitor) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.addProfile(profileId, properties);
}
public static void removeProfile(String profileId, IProgressMonitor monitor) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
profileRegistry.removeProfile(profileId);
}
public static IProfile[] getProfiles() throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfiles();
}
public static long[] getProfileTimestamps(String id) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.listProfileTimestamps(id);
}
public static IProfile getProfile(String id) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfile(id);
}
public static IProfile getProfile(String id, long timestamp) throws ProvisionException {
IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper.getService(ProvUIActivator.getContext(), IProfileRegistry.class.getName());
if (profileRegistry == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoProfileRegistryFound);
}
return profileRegistry.getProfile(id, timestamp);
}
public static URI[] getMetadataRepositories(int flags) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getKnownRepositories(flags);
}
public static void refreshMetadataRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100);
for (int i = 0; i < urls.length; i++) {
try {
manager.refreshRepository(urls[i], mon.newChild(100));
} catch (ProvisionException e) {
//ignore problematic repositories when refreshing
}
}
}
public static URI[] getArtifactRepositories(int flags) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
return manager.getKnownRepositories(flags);
}
public static void refreshArtifactRepositories(URI[] urls, IProgressMonitor monitor) throws ProvisionException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoRepositoryManager);
}
SubMonitor mon = SubMonitor.convert(monitor, urls.length * 100);
for (int i = 0; i < urls.length; i++) {
manager.refreshRepository(urls[i], mon.newChild(100));
}
}
/*
* Get the plan for the specified install operation
*/
public static ProvisioningPlan getProvisioningPlan(ProfileChangeRequest request, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
try {
return getPlanner().getProvisioningPlan(request, context, monitor);
} catch (OperationCanceledException e) {
return null;
}
}
/*
* Get a plan for reverting to a specified profile snapshot
*/
public static ProvisioningPlan getRevertPlan(IProfile currentProfile, IProfile snapshot, IProgressMonitor monitor) throws ProvisionException {
Assert.isNotNull(currentProfile);
Assert.isNotNull(snapshot);
return getPlanner().getDiffPlan(currentProfile, snapshot, monitor);
}
/*
* Get sizing info for the specified plan
*/
public static long getSize(ProvisioningPlan plan, String profileId, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
// If there is nothing to size, return 0
if (plan == null)
return IIUElement.SIZE_NOTAPPLICABLE;
if (plan.getOperands().length == 0)
return 0;
SizingPhaseSet set = new SizingPhaseSet();
IStatus status = getEngine().perform(getProfile(profileId), set, plan.getOperands(), context, monitor);
if (status.isOK())
return set.getSizing().getDiskSize();
return IIUElement.SIZE_UNAVAILABLE;
}
public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 100 ticks for install plan, 200 for the actual install
SubMonitor mon = SubMonitor.convert(monitor, 300);
if (plan.getInstallerPlan() != null) {
IStatus installerPlanStatus = getEngine().perform(plan.getInstallerPlan().getProfileChangeRequest().getProfile(), phaseSet, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
+ // The profile has changed, so we need a new snapshot.
+ profile = getProfile(profile.getProfileId());
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
} else {
mon.worked(100);
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(200));
}
private static IEngine getEngine() throws ProvisionException {
IEngine engine = (IEngine) ServiceHelper.getService(ProvUIActivator.getContext(), IEngine.SERVICE_NAME);
if (engine == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoEngineFound);
}
return engine;
}
public static IPlanner getPlanner() throws ProvisionException {
IPlanner planner = (IPlanner) ServiceHelper.getService(ProvUIActivator.getContext(), IPlanner.class.getName());
if (planner == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoPlannerFound);
}
return planner;
}
public static IDirector getDirector() throws ProvisionException {
IDirector director = (IDirector) ServiceHelper.getService(ProvUIActivator.getContext(), IDirector.class.getName());
if (director == null) {
throw new ProvisionException(ProvUIMessages.ProvisioningUtil_NoDirectorFound);
}
return director;
}
public static void setColocatedRepositoryEnablement(URI location, boolean enabled) {
IMetadataRepositoryManager metaManager = (IMetadataRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IMetadataRepositoryManager.class.getName());
if (metaManager != null)
metaManager.setEnabled(location, enabled);
IArtifactRepositoryManager artifactManager = (IArtifactRepositoryManager) ServiceHelper.getService(ProvUIActivator.getContext(), IArtifactRepositoryManager.class.getName());
if (artifactManager != null)
artifactManager.setEnabled(location, enabled);
}
public static boolean isCategory(IInstallableUnit iu) {
String isCategory = iu.getProperty(IInstallableUnit.PROP_TYPE_CATEGORY);
return isCategory != null && Boolean.valueOf(isCategory).booleanValue();
}
/**
* Perform the provisioning plan using a default context that contacts all repositories.
* @param plan the plan to perform
* @param phaseSet the phase set to use
* @param profile the profile to be changed
* @param monitor the progress monitor
* @return a status indicating the success of the plan
* @throws ProvisionException
*
* @deprecated clients should use {@linkplain #performProvisioningPlan(ProvisioningPlan, PhaseSet, IProfile, ProvisioningContext, IProgressMonitor)}
* to explicitly establish a provisioning context. Otherwise all repositories will be contacted
*/
public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
return getEngine().perform(profile, set, plan.getOperands(), new ProvisioningContext(), monitor);
}
}
| true | true | public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 100 ticks for install plan, 200 for the actual install
SubMonitor mon = SubMonitor.convert(monitor, 300);
if (plan.getInstallerPlan() != null) {
IStatus installerPlanStatus = getEngine().perform(plan.getInstallerPlan().getProfileChangeRequest().getProfile(), phaseSet, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
} else {
mon.worked(100);
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(200));
}
| public static IStatus performProvisioningPlan(ProvisioningPlan plan, PhaseSet phaseSet, IProfile profile, ProvisioningContext context, IProgressMonitor monitor) throws ProvisionException {
PhaseSet set;
if (phaseSet == null)
set = new DefaultPhaseSet();
else
set = phaseSet;
// 100 ticks for install plan, 200 for the actual install
SubMonitor mon = SubMonitor.convert(monitor, 300);
if (plan.getInstallerPlan() != null) {
IStatus installerPlanStatus = getEngine().perform(plan.getInstallerPlan().getProfileChangeRequest().getProfile(), phaseSet, plan.getInstallerPlan().getOperands(), context, mon.newChild(100));
if (!installerPlanStatus.isOK()) {
mon.done();
return installerPlanStatus;
}
Configurator configChanger = (Configurator) ServiceHelper.getService(ProvUIActivator.getContext(), Configurator.class.getName());
try {
ProvisioningOperationRunner.suppressRestart(true);
configChanger.applyConfiguration();
// The profile has changed, so we need a new snapshot.
profile = getProfile(profile.getProfileId());
} catch (IOException e) {
mon.done();
return new Status(IStatus.ERROR, ProvUIActivator.PLUGIN_ID, ProvUIMessages.ProvisioningUtil_InstallPlanConfigurationError, e);
} finally {
ProvisioningOperationRunner.suppressRestart(false);
}
} else {
mon.worked(100);
}
return getEngine().perform(profile, set, plan.getOperands(), context, mon.newChild(200));
}
|
diff --git a/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java b/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
index 335381ec7..972befb54 100644
--- a/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
+++ b/src/main/java/biomesoplenty/integration/TreeCapitatorIntegration.java
@@ -1,187 +1,187 @@
package biomesoplenty.integration;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import biomesoplenty.api.Blocks;
import biomesoplenty.api.Items;
import cpw.mods.fml.common.event.FMLInterModComms;
public class TreeCapitatorIntegration
{
public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
int leavesColorized3 = Blocks.leavesColorized3.get().blockID;
int leavesColorized4 = Blocks.leavesColorized4.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
- tree.setString("leaves", String.format("%d,0", leavesColorized1));
+ tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
- tree.setString("leaves", String.format("%d,1; %d,3", leaves3, leaves3));
+ tree.setString("leaves", String.format("%d,1; %d,9; %d,3; %d,11", leaves3, leaves3, leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
- tree.setString("leaves", String.format("%d,3", leaves1));
+ tree.setString("leaves", String.format("%d,3; %d,11", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
- tree.setString("leaves", String.format("%d,2", leaves2));
+ tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
}
| false | true | public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
int leavesColorized3 = Blocks.leavesColorized3.get().blockID;
int leavesColorized4 = Blocks.leavesColorized4.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,0", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,1; %d,3", leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,3", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,2", leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
| public static void init()
{
int logs1 = Blocks.logs1.get().blockID;
int logs2 = Blocks.logs2.get().blockID;
int logs3 = Blocks.logs3.get().blockID;
int logs4 = Blocks.logs4.get().blockID;
int leavesColorized1 = Blocks.leavesColorized1.get().blockID;
int leavesColorized2 = Blocks.leavesColorized2.get().blockID;
int leavesColorized3 = Blocks.leavesColorized3.get().blockID;
int leavesColorized4 = Blocks.leavesColorized4.get().blockID;
int leaves1 = Blocks.leaves1.get().blockID;
int leaves2 = Blocks.leaves2.get().blockID;
int leaves3 = Blocks.leaves3.get().blockID;
int leaves4 = Blocks.leaves4.get().blockID;
NBTTagCompound tpModCfg = new NBTTagCompound();
tpModCfg.setString("modID", "BiomesOPlenty");
tpModCfg.setString("axeIDList", Items.axeAmethyst.get().itemID + "; " + Items.axeMud.get().itemID);
NBTTagList treeList = new NBTTagList();
/*
* NOTE: the vanilla trees (any tree that contains a vanilla log) are the only ones where treeName must be one of these values:
* vanilla_oak, vanilla_spruce, vanilla_birch, vanilla_jungle.
*/
// Vanilla Oak additions
NBTTagCompound tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_oak");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0; %d,3; %d; %d,0; %d,0; %d,2; 18,2; 18,10",
leaves2, leaves2, Blocks.leavesFruit.get().blockID, Blocks.leavesFruit2.get().blockID, leaves2, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Birch additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_birch");
tree.setString("logs", "");
tree.setString("leaves", String.format("%d,0", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// Vanilla Jungle additions
tree = new NBTTagCompound();
tree.setString("treeName", "vanilla_jungle");
tree.setString("logs", "");
tree.setString("leaves", "");
tree.setInteger("maxLeafIDDist", 3);
treeList.appendTag(tree);
/*
* logs1 trees
*/
// BoP acacia
tree = new NBTTagCompound();
tree.setString("treeName", "acacia");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,0; %d,8", leavesColorized1, leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP cherry
tree = new NBTTagCompound();
tree.setString("treeName", "cherry");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,1; %d,9; %d,3; %d,11", leaves3, leaves3, leaves3, leaves3));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP darkwood
tree = new NBTTagCompound();
tree.setString("treeName", "darkwood");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,3; %d,11", leaves1, leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP fir
tree = new NBTTagCompound();
tree.setString("treeName", "fir");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs1, logs1, logs1));
tree.setString("leaves", String.format("%d,2; %d,10", leaves2, leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs2 trees
*/
// BoP holy
tree = new NBTTagCompound();
tree.setString("treeName", "holy");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP magic
tree = new NBTTagCompound();
tree.setString("treeName", "magic");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leaves1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP mangrove
tree = new NBTTagCompound();
tree.setString("treeName", "mangrove");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,1", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP palm
tree = new NBTTagCompound();
tree.setString("treeName", "palm");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs2, logs2, logs2));
tree.setString("leaves", String.format("%d,2", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs3 trees
*/
// BoP redwood
tree = new NBTTagCompound();
tree.setString("treeName", "redwood");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,3", leavesColorized1));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP willow
tree = new NBTTagCompound();
tree.setString("treeName", "willow");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs3, logs3, logs3));
tree.setString("leaves", String.format("%d,0", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP dead
tree = new NBTTagCompound();
tree.setString("treeName", "dead");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs3, logs3, logs3));
tree.setString("leaves", "");
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP big_flower
tree = new NBTTagCompound();
tree.setString("treeName", "big_flower");
tree.setString("logs", String.format("%d,3; %d,7; %d,11", logs3, logs3, logs3));
tree.setString("leaves", "" + Blocks.petals.get().blockID);
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
/*
* logs4 trees
*/
// BoP pine
tree = new NBTTagCompound();
tree.setString("treeName", "pine");
tree.setString("logs", String.format("%d,0; %d,4; %d,8", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,2", leavesColorized2));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP hellbark
tree = new NBTTagCompound();
tree.setString("treeName", "hellbark");
tree.setString("logs", String.format("%d,1; %d,5; %d,9", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,0", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
// BoP jacaranda
tree = new NBTTagCompound();
tree.setString("treeName", "jacaranda");
tree.setString("logs", String.format("%d,2; %d,6; %d,10", logs4, logs4, logs4));
tree.setString("leaves", String.format("%d,1", leaves4));
tree.setBoolean("requireLeafDecayCheck", false);
treeList.appendTag(tree);
tpModCfg.setTag("trees", treeList);
FMLInterModComms.sendMessage("TreeCapitator", "ThirdPartyModConfig", tpModCfg);
}
|
diff --git a/software/camod/src/gov/nih/nci/camod/util/AuthenticationFilter.java b/software/camod/src/gov/nih/nci/camod/util/AuthenticationFilter.java
index f62dc4b2..8720cc2c 100755
--- a/software/camod/src/gov/nih/nci/camod/util/AuthenticationFilter.java
+++ b/software/camod/src/gov/nih/nci/camod/util/AuthenticationFilter.java
@@ -1,138 +1,140 @@
/**
*
* $Id: AuthenticationFilter.java,v 1.7 2008-08-14 17:12:21 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.6 2006/11/09 17:33:19 pandyas
* Commented out debug code
*
* Revision 1.5 2006/04/17 19:10:50 pandyas
* Added $Id: AuthenticationFilter.java,v 1.7 2008-08-14 17:12:21 pandyas Exp $ and $log:$
*
*
*/
package gov.nih.nci.camod.util;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;
public class AuthenticationFilter implements Filter {
private FilterConfig filterConfig;
/**
* Called by the web container to indicate to a filter that it is being
* placed into service.
*/
public void init(FilterConfig filterConfig) throws ServletException {
//System.out.println("AuthenticationFilter.init");
this.filterConfig = filterConfig;
}
/**
* The doFilter method of the Filter is called by the web container each time a
* request/response pair is passed through the chain due to a client request
* for a resource at the end of the chain.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
- System.out.println("AuthenticationFilter.doFilter");
+ //System.out.println("AuthenticationFilter.doFilter");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
System.out.println("req.getServletPath()= " + req.getServletPath());
System.out.println("Enter doFilter req.getSession().getId()= " + req.getSession().getId());
- System.out.println("Enter doFilter notloggedin= " + (String)req.getSession().getAttribute("notloggedin"));
+ System.out.println("Enter doFilter notloggedin= " + (String)req.getSession().getAttribute("notloggedin"));
boolean authorized = false;
String isloginpage = ((HttpServletRequest) request).getRequestURI();
System.out.println("AuthenticationFilter.doFilter isloginpage= " + isloginpage);
boolean isRequestedSessionIdFromURL = ((HttpServletRequest) request).isRequestedSessionIdFromURL();
System.out.println("AuthenticationFilter.doFilter isRequestedSessionIdFromURL= " + isRequestedSessionIdFromURL);
if (request instanceof HttpServletRequest) {
if(isloginpage!=null && !isRequestedSessionIdFromURL &&(
- isloginpage.endsWith("loginMain.do")
+ isloginpage.endsWith("loginMain.do") ||
+ isloginpage.endsWith("LoginAction.do") ||
+ isloginpage.endsWith("/camod/LoginAction.do")
)) {
- System.out.println("AuthenticationFilter.doFilter login.do loop ");
+ System.out.println("AuthenticationFilter.doFilter loginMain.do,LoginAction.do,/camod/LoginAction.do loop ");
//just continue, so they can login
generateNewSession((HttpServletRequest) request);
chain.doFilter(request, response);
return;
}
System.out.println("AuthenticationFilter.doFilter NOT login.do or loginMain.do ");
//check login for caMOD
HttpSession session = ((HttpServletRequest) request).getSession(false);
System.out.println("AuthenticationFilter.doFilter session= " + session);
if (session != null && !isRequestedSessionIdFromURL){
String loggedin = (String)session.getAttribute("loggedin");
System.out.println("AuthenticationFilter loggedin= " + loggedin);
// reverse this property in application when this code works
if(loggedin != null && loggedin.equals("true")){
System.out.println("AuthenticationFilter set authorized = true: " );
authorized = true;
}
}
}
if (authorized) {
System.out.println("AuthenticationFilter.doFilter authorized loop");
chain.doFilter(request, response);
return;
} else if (filterConfig != null) {
// redirect to login.jsp from any unauthorized pages (external bookmarks to secure pages, ect)
String unauthorizedPage = filterConfig.getInitParameter("unauthorizedPage");
System.out.println("AuthenticationFilter.doFilter not authorized loop unauthorizedPage= " + unauthorizedPage);
if (unauthorizedPage != null && !"".equals(unauthorizedPage)) {
- //System.out.println("unauthorizedPage != null && !.equals(unauthorizedPage) loop: ");
+ System.out.println("unauthorizedPage != null && !.equals(unauthorizedPage) loop: ");
generateNewSession((HttpServletRequest) request);
System.out.println("Generated new session for request ");
//chain.doFilter(request, response);
chain.doFilter(request, response);
return;
}
}
}
private void generateNewSession(HttpServletRequest httpRequest){
System.out.println("AuthenticationFilter generateNewSession enter");
HttpSession session = httpRequest.getSession();
HashMap<String, Object> old = new HashMap<String, Object>();
Enumeration<String> keys = (Enumeration<String>) session.getAttributeNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
old.put(key, session.getAttribute(key));
}
//session invalidated
session.invalidate();
// get new session
session = httpRequest.getSession(true);
for (Map.Entry<String, Object> entry : old.entrySet()) {
session.setAttribute(entry.getKey(), entry.getValue());
}
System.out.println("AuthenticationFilter generateNewSession exit");
}
/**
* Called by the web container to indicate to a filter that it is being
* taken out of service.
*/
public void destroy() {
filterConfig = null;
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
System.out.println("AuthenticationFilter.doFilter");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
System.out.println("req.getServletPath()= " + req.getServletPath());
System.out.println("Enter doFilter req.getSession().getId()= " + req.getSession().getId());
System.out.println("Enter doFilter notloggedin= " + (String)req.getSession().getAttribute("notloggedin"));
boolean authorized = false;
String isloginpage = ((HttpServletRequest) request).getRequestURI();
System.out.println("AuthenticationFilter.doFilter isloginpage= " + isloginpage);
boolean isRequestedSessionIdFromURL = ((HttpServletRequest) request).isRequestedSessionIdFromURL();
System.out.println("AuthenticationFilter.doFilter isRequestedSessionIdFromURL= " + isRequestedSessionIdFromURL);
if (request instanceof HttpServletRequest) {
if(isloginpage!=null && !isRequestedSessionIdFromURL &&(
isloginpage.endsWith("loginMain.do")
)) {
System.out.println("AuthenticationFilter.doFilter login.do loop ");
//just continue, so they can login
generateNewSession((HttpServletRequest) request);
chain.doFilter(request, response);
return;
}
System.out.println("AuthenticationFilter.doFilter NOT login.do or loginMain.do ");
//check login for caMOD
HttpSession session = ((HttpServletRequest) request).getSession(false);
System.out.println("AuthenticationFilter.doFilter session= " + session);
if (session != null && !isRequestedSessionIdFromURL){
String loggedin = (String)session.getAttribute("loggedin");
System.out.println("AuthenticationFilter loggedin= " + loggedin);
// reverse this property in application when this code works
if(loggedin != null && loggedin.equals("true")){
System.out.println("AuthenticationFilter set authorized = true: " );
authorized = true;
}
}
}
if (authorized) {
System.out.println("AuthenticationFilter.doFilter authorized loop");
chain.doFilter(request, response);
return;
} else if (filterConfig != null) {
// redirect to login.jsp from any unauthorized pages (external bookmarks to secure pages, ect)
String unauthorizedPage = filterConfig.getInitParameter("unauthorizedPage");
System.out.println("AuthenticationFilter.doFilter not authorized loop unauthorizedPage= " + unauthorizedPage);
if (unauthorizedPage != null && !"".equals(unauthorizedPage)) {
//System.out.println("unauthorizedPage != null && !.equals(unauthorizedPage) loop: ");
generateNewSession((HttpServletRequest) request);
System.out.println("Generated new session for request ");
//chain.doFilter(request, response);
chain.doFilter(request, response);
return;
}
}
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
//System.out.println("AuthenticationFilter.doFilter");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
System.out.println("req.getServletPath()= " + req.getServletPath());
System.out.println("Enter doFilter req.getSession().getId()= " + req.getSession().getId());
System.out.println("Enter doFilter notloggedin= " + (String)req.getSession().getAttribute("notloggedin"));
boolean authorized = false;
String isloginpage = ((HttpServletRequest) request).getRequestURI();
System.out.println("AuthenticationFilter.doFilter isloginpage= " + isloginpage);
boolean isRequestedSessionIdFromURL = ((HttpServletRequest) request).isRequestedSessionIdFromURL();
System.out.println("AuthenticationFilter.doFilter isRequestedSessionIdFromURL= " + isRequestedSessionIdFromURL);
if (request instanceof HttpServletRequest) {
if(isloginpage!=null && !isRequestedSessionIdFromURL &&(
isloginpage.endsWith("loginMain.do") ||
isloginpage.endsWith("LoginAction.do") ||
isloginpage.endsWith("/camod/LoginAction.do")
)) {
System.out.println("AuthenticationFilter.doFilter loginMain.do,LoginAction.do,/camod/LoginAction.do loop ");
//just continue, so they can login
generateNewSession((HttpServletRequest) request);
chain.doFilter(request, response);
return;
}
System.out.println("AuthenticationFilter.doFilter NOT login.do or loginMain.do ");
//check login for caMOD
HttpSession session = ((HttpServletRequest) request).getSession(false);
System.out.println("AuthenticationFilter.doFilter session= " + session);
if (session != null && !isRequestedSessionIdFromURL){
String loggedin = (String)session.getAttribute("loggedin");
System.out.println("AuthenticationFilter loggedin= " + loggedin);
// reverse this property in application when this code works
if(loggedin != null && loggedin.equals("true")){
System.out.println("AuthenticationFilter set authorized = true: " );
authorized = true;
}
}
}
if (authorized) {
System.out.println("AuthenticationFilter.doFilter authorized loop");
chain.doFilter(request, response);
return;
} else if (filterConfig != null) {
// redirect to login.jsp from any unauthorized pages (external bookmarks to secure pages, ect)
String unauthorizedPage = filterConfig.getInitParameter("unauthorizedPage");
System.out.println("AuthenticationFilter.doFilter not authorized loop unauthorizedPage= " + unauthorizedPage);
if (unauthorizedPage != null && !"".equals(unauthorizedPage)) {
System.out.println("unauthorizedPage != null && !.equals(unauthorizedPage) loop: ");
generateNewSession((HttpServletRequest) request);
System.out.println("Generated new session for request ");
//chain.doFilter(request, response);
chain.doFilter(request, response);
return;
}
}
}
|
diff --git a/sonar-server/src/main/java/org/sonar/server/search/SearchNode.java b/sonar-server/src/main/java/org/sonar/server/search/SearchNode.java
index 633249e027..fa7cbfd1b8 100644
--- a/sonar-server/src/main/java/org/sonar/server/search/SearchNode.java
+++ b/sonar-server/src/main/java/org/sonar/server/search/SearchNode.java
@@ -1,143 +1,143 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.search;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.io.FileUtils;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.logging.slf4j.Slf4jESLoggerFactory;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.picocontainer.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.Settings;
import org.sonar.api.platform.ServerFileSystem;
import java.io.File;
/**
* Manages the ElasticSearch Node instance used to connect to the index.
* @since 4.1
*/
public class SearchNode implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(SearchIndex.class);
private static final String HTTP_ENABLED = "http.enabled";
private static final String INSTANCE_NAME = "sonarqube";
static final String DATA_DIR = "data/es";
private static final String DEFAULT_HEALTH_TIMEOUT = "30s";
private final ServerFileSystem fileSystem;
private final Settings settings;
private final String healthTimeout;
// available only after startup
private Node node;
public SearchNode(ServerFileSystem fileSystem, Settings settings) {
this(fileSystem, settings, DEFAULT_HEALTH_TIMEOUT);
}
@VisibleForTesting
SearchNode(ServerFileSystem fileSystem, Settings settings, String healthTimeout) {
this.fileSystem = fileSystem;
this.settings = settings;
this.healthTimeout = healthTimeout;
}
@Override
public void start() {
LOG.info("Starting Elasticsearch...");
initLogging();
ImmutableSettings.Builder esSettings = ImmutableSettings.builder().put("node.name", INSTANCE_NAME);
initDirs(esSettings);
initRestConsole(esSettings);
node = NodeBuilder.nodeBuilder()
.clusterName(INSTANCE_NAME)
.local(true)
.data(true)
.settings(esSettings)
.node();
node.start();
if (
node.client().admin().cluster().prepareHealth()
.setWaitForYellowStatus()
.setTimeout(healthTimeout)
.execute().actionGet()
.getStatus() == ClusterHealthStatus.RED) {
throw new IllegalStateException(
- String.format("Elasticsearch index is corrupt, please delete directory '${SonarQubeHomeDirectory}/%s' and relaunch the SonarQube server.", DATA_DIR));
+ String.format("Elasticsearch index is corrupt, please delete directory '%s/%s' and relaunch the SonarQube server.", fileSystem.getHomeDir().getAbsolutePath(), DATA_DIR));
}
LOG.info("Elasticsearch started");
}
private void initLogging() {
ESLoggerFactory.setDefaultFactory(new Slf4jESLoggerFactory());
}
private void initRestConsole(ImmutableSettings.Builder esSettings) {
int httpPort = settings.getInt("sonar.es.http.port");
if (httpPort > 0) {
LOG.warn("Elasticsearch HTTP console enabled on port {}. Only for debugging purpose.", httpPort);
esSettings.put(HTTP_ENABLED, true);
esSettings.put("http.host", "127.0.0.1");
esSettings.put("http.port", httpPort);
} else {
esSettings.put(HTTP_ENABLED, false);
}
}
private void initDirs(ImmutableSettings.Builder esSettings) {
File esDir = new File(fileSystem.getHomeDir(), DATA_DIR);
try {
FileUtils.forceMkdir(esDir);
esSettings.put("path.home", esDir.getAbsolutePath());
LOG.debug("Elasticsearch data stored in {}", esDir.getAbsolutePath());
} catch (Exception e) {
throw new IllegalStateException("Fail to create directory " + esDir.getAbsolutePath(), e);
}
}
@Override
public void stop() {
if (node != null) {
node.close();
node = null;
}
}
public Client client() {
if (node == null) {
throw new IllegalStateException("Elasticsearch is not started");
}
return node.client();
}
}
| true | true | public void start() {
LOG.info("Starting Elasticsearch...");
initLogging();
ImmutableSettings.Builder esSettings = ImmutableSettings.builder().put("node.name", INSTANCE_NAME);
initDirs(esSettings);
initRestConsole(esSettings);
node = NodeBuilder.nodeBuilder()
.clusterName(INSTANCE_NAME)
.local(true)
.data(true)
.settings(esSettings)
.node();
node.start();
if (
node.client().admin().cluster().prepareHealth()
.setWaitForYellowStatus()
.setTimeout(healthTimeout)
.execute().actionGet()
.getStatus() == ClusterHealthStatus.RED) {
throw new IllegalStateException(
String.format("Elasticsearch index is corrupt, please delete directory '${SonarQubeHomeDirectory}/%s' and relaunch the SonarQube server.", DATA_DIR));
}
LOG.info("Elasticsearch started");
}
| public void start() {
LOG.info("Starting Elasticsearch...");
initLogging();
ImmutableSettings.Builder esSettings = ImmutableSettings.builder().put("node.name", INSTANCE_NAME);
initDirs(esSettings);
initRestConsole(esSettings);
node = NodeBuilder.nodeBuilder()
.clusterName(INSTANCE_NAME)
.local(true)
.data(true)
.settings(esSettings)
.node();
node.start();
if (
node.client().admin().cluster().prepareHealth()
.setWaitForYellowStatus()
.setTimeout(healthTimeout)
.execute().actionGet()
.getStatus() == ClusterHealthStatus.RED) {
throw new IllegalStateException(
String.format("Elasticsearch index is corrupt, please delete directory '%s/%s' and relaunch the SonarQube server.", fileSystem.getHomeDir().getAbsolutePath(), DATA_DIR));
}
LOG.info("Elasticsearch started");
}
|
diff --git a/src/main/java/fr/jamgotchian/abcd/core/controlflow/ExceptionTable.java b/src/main/java/fr/jamgotchian/abcd/core/controlflow/ExceptionTable.java
index 74f6d25..5eea252 100644
--- a/src/main/java/fr/jamgotchian/abcd/core/controlflow/ExceptionTable.java
+++ b/src/main/java/fr/jamgotchian/abcd/core/controlflow/ExceptionTable.java
@@ -1,103 +1,103 @@
/*
* Copyright (C) 2011 Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*
* 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 fr.jamgotchian.abcd.core.controlflow;
import fr.jamgotchian.abcd.core.util.ConsoleUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*/
public class ExceptionTable {
public static class Entry {
private final int tryStart;
private final int tryEnd;
private final int catchStart;
private final String exceptionClassName;
public Entry(int tryStart, int tryEnd, int catchStart, String exceptionClassName) {
if (tryEnd <= tryStart) {
throw new IllegalArgumentException("tryEnd <= tryStart");
}
if (catchStart < tryEnd) {
throw new IllegalArgumentException("catchStart < tryEnd");
}
this.tryStart = tryStart;
this.tryEnd = tryEnd;
this.catchStart = catchStart;
this.exceptionClassName = exceptionClassName;
}
public int getTryStart() {
return tryStart;
}
public int getTryEnd() {
return tryEnd;
}
public int getCatchStart() {
return catchStart;
}
public String getExceptionClassName() {
return exceptionClassName;
}
}
private final List<Entry> entries = new ArrayList<ExceptionTable.Entry>();
public void addEntry(int tryStart, int tryEnd, int catchStart, String exceptionClassName) {
entries.add(new Entry(tryStart, tryEnd, catchStart, exceptionClassName));
}
public List<Entry> getEntries() {
return Collections.unmodifiableList(entries);
}
public void print(StringBuilder builder) {
int rowCount = entries.size() + 1;
List<String> tryStartColumn = new ArrayList<String>(rowCount);
List<String> tryEndColumn = new ArrayList<String>(rowCount);
List<String> catchStartColumn = new ArrayList<String>(rowCount);
List<String> typeColumn = new ArrayList<String>(rowCount);
tryStartColumn.add("tryStart");
- tryEndColumn.add("endStart");
+ tryEndColumn.add("tryEnd");
catchStartColumn.add("catchStart");
typeColumn.add("type");
for (int i = 0; i < entries.size(); i++) {
Entry entry = entries.get(i);
- tryStartColumn.add(Integer.toString(entry.getCatchStart()));
+ tryStartColumn.add(Integer.toString(entry.getTryStart()));
tryEndColumn.add(Integer.toString(entry.getTryEnd()));
catchStartColumn.add(Integer.toString(entry.getCatchStart()));
typeColumn.add(entry.getExceptionClassName());
}
ConsoleUtil.printTable(builder, tryStartColumn, tryEndColumn,
catchStartColumn, typeColumn);
}
}
| false | true | public void print(StringBuilder builder) {
int rowCount = entries.size() + 1;
List<String> tryStartColumn = new ArrayList<String>(rowCount);
List<String> tryEndColumn = new ArrayList<String>(rowCount);
List<String> catchStartColumn = new ArrayList<String>(rowCount);
List<String> typeColumn = new ArrayList<String>(rowCount);
tryStartColumn.add("tryStart");
tryEndColumn.add("endStart");
catchStartColumn.add("catchStart");
typeColumn.add("type");
for (int i = 0; i < entries.size(); i++) {
Entry entry = entries.get(i);
tryStartColumn.add(Integer.toString(entry.getCatchStart()));
tryEndColumn.add(Integer.toString(entry.getTryEnd()));
catchStartColumn.add(Integer.toString(entry.getCatchStart()));
typeColumn.add(entry.getExceptionClassName());
}
ConsoleUtil.printTable(builder, tryStartColumn, tryEndColumn,
catchStartColumn, typeColumn);
}
| public void print(StringBuilder builder) {
int rowCount = entries.size() + 1;
List<String> tryStartColumn = new ArrayList<String>(rowCount);
List<String> tryEndColumn = new ArrayList<String>(rowCount);
List<String> catchStartColumn = new ArrayList<String>(rowCount);
List<String> typeColumn = new ArrayList<String>(rowCount);
tryStartColumn.add("tryStart");
tryEndColumn.add("tryEnd");
catchStartColumn.add("catchStart");
typeColumn.add("type");
for (int i = 0; i < entries.size(); i++) {
Entry entry = entries.get(i);
tryStartColumn.add(Integer.toString(entry.getTryStart()));
tryEndColumn.add(Integer.toString(entry.getTryEnd()));
catchStartColumn.add(Integer.toString(entry.getCatchStart()));
typeColumn.add(entry.getExceptionClassName());
}
ConsoleUtil.printTable(builder, tryStartColumn, tryEndColumn,
catchStartColumn, typeColumn);
}
|
diff --git a/agave/agave-archetype/src/main/resources/archetype-resources/src/main/java/WelcomeHandler.java b/agave/agave-archetype/src/main/resources/archetype-resources/src/main/java/WelcomeHandler.java
index f534e17..2c7282a 100644
--- a/agave/agave-archetype/src/main/resources/archetype-resources/src/main/java/WelcomeHandler.java
+++ b/agave/agave-archetype/src/main/resources/archetype-resources/src/main/java/WelcomeHandler.java
@@ -1,35 +1,35 @@
package $package;
import agave.AbstractHandler;
import agave.HandlesRequestsTo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class WelcomeHandler extends AbstractHandler {
@HandlesRequestsTo("/")
public void welcome() throws Exception {
response.setContentType("application/xhtml+xml");
String context = request.getContextPath().substring(1);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
out.println(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
out.println(" <head>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
- out.format(" <title>Hello, {0}!</title>", context);
+ out.format(" <title>Hello, %s!</title>\n", context);
out.println(" </head>");
out.println(" <body>");
- out.format(" <p>Hello, {0}!</p>", context);
+ out.format(" <p>Hello, %s!</p>\n", context);
out.println(" </body>");
out.println("</html>");
out.close();
}
}
| false | true | public void welcome() throws Exception {
response.setContentType("application/xhtml+xml");
String context = request.getContextPath().substring(1);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
out.println(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
out.println(" <head>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
out.format(" <title>Hello, {0}!</title>", context);
out.println(" </head>");
out.println(" <body>");
out.format(" <p>Hello, {0}!</p>", context);
out.println(" </body>");
out.println("</html>");
out.close();
}
| public void welcome() throws Exception {
response.setContentType("application/xhtml+xml");
String context = request.getContextPath().substring(1);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
out.println(" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
out.println(" <head>");
out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
out.format(" <title>Hello, %s!</title>\n", context);
out.println(" </head>");
out.println(" <body>");
out.format(" <p>Hello, %s!</p>\n", context);
out.println(" </body>");
out.println("</html>");
out.close();
}
|
diff --git a/runtime/src/com/sun/xml/bind/v2/model/impl/PropertyInfoImpl.java b/runtime/src/com/sun/xml/bind/v2/model/impl/PropertyInfoImpl.java
index d7e6bebd..9a41989a 100644
--- a/runtime/src/com/sun/xml/bind/v2/model/impl/PropertyInfoImpl.java
+++ b/runtime/src/com/sun/xml/bind/v2/model/impl/PropertyInfoImpl.java
@@ -1,397 +1,397 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.bind.v2.model.impl;
import java.util.Collection;
import java.lang.annotation.Annotation;
import javax.activation.MimeType;
import javax.xml.bind.annotation.XmlAttachmentRef;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import javax.xml.bind.annotation.XmlInlineBinaryData;
import javax.xml.bind.annotation.XmlMimeType;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.namespace.QName;
import com.sun.xml.bind.v2.TODO;
import com.sun.xml.bind.v2.model.annotation.AnnotationReader;
import com.sun.xml.bind.v2.model.annotation.Locatable;
import com.sun.xml.bind.v2.model.core.Adapter;
import com.sun.xml.bind.v2.model.core.ID;
import com.sun.xml.bind.v2.model.core.PropertyInfo;
import com.sun.xml.bind.v2.model.core.TypeInfo;
import com.sun.xml.bind.v2.model.core.TypeInfoSet;
import com.sun.xml.bind.v2.model.nav.Navigator;
import com.sun.xml.bind.v2.runtime.IllegalAnnotationException;
import com.sun.xml.bind.v2.runtime.Location;
import com.sun.xml.bind.v2.runtime.SwaRefAdapter;
/**
* Default partial implementation for {@link PropertyInfo}.
*
* @author Kohsuke Kawaguchi
*/
abstract class PropertyInfoImpl<T,C,F,M>
implements PropertyInfo<T,C>, Locatable, Comparable<PropertyInfoImpl> /*by their names*/ {
/**
* Object that reads annotations.
*/
protected final PropertySeed<T,C,F,M> seed;
private final boolean isCollection;
private final ID id;
private final MimeType expectedMimeType;
private final boolean inlineBinary;
private final QName schemaType;
protected final ClassInfoImpl<T,C,F,M> parent;
private final Adapter<T,C> adapter;
protected PropertyInfoImpl(ClassInfoImpl<T,C,F,M> parent, PropertySeed<T,C,F,M> spi) {
this.seed = spi;
this.parent = parent;
if(parent==null)
/*
Various people reported a bug where this parameter is somehow null.
In an attempt to catch the error better, let's do an explicit check here.
http://forums.java.net/jive/thread.jspa?threadID=18479
http://forums.java.net/jive/thread.jspa?messageID=165946
*/
throw new AssertionError();
MimeType mt = Util.calcExpectedMediaType(seed,parent.builder);
if(mt!=null && !kind().canHaveXmlMimeType) {
parent.builder.reportError(new IllegalAnnotationException(
Messages.ILLEGAL_ANNOTATION.format(XmlMimeType.class.getName()),
seed.readAnnotation(XmlMimeType.class)
));
mt = null;
}
this.expectedMimeType = mt;
this.inlineBinary = seed.hasAnnotation(XmlInlineBinaryData.class);
- this.schemaType = Util.calcSchemaType(reader(),seed,parent.clazz,
- getIndividualType(),this);
T t = seed.getRawType();
// check if there's an adapter applicable to the whole property
XmlJavaTypeAdapter xjta = getApplicableAdapter(t);
if(xjta!=null) {
isCollection = false;
adapter = new Adapter<T,C>(xjta,reader(),nav());
} else {
// check if the adapter is applicable to the individual item in the property
this.isCollection = nav().isSubClassOf(t, nav().ref(Collection.class))
|| nav().isArrayButNotByteArray(t);
xjta = getApplicableAdapter(getIndividualType());
if(xjta==null) {
// ugly ugly hack, but we implement swaRef as adapter
XmlAttachmentRef xsa = seed.readAnnotation(XmlAttachmentRef.class);
if(xsa!=null) {
parent.builder.hasSwaRef = true;
adapter = new Adapter<T,C>(nav().asDecl(SwaRefAdapter.class),nav());
} else {
adapter = null;
// if this field has adapter annotation but not applicable,
// that must be an error of the user
xjta = seed.readAnnotation(XmlJavaTypeAdapter.class);
if(xjta!=null) {
T adapter = reader().getClassValue(xjta,"value");
parent.builder.reportError(new IllegalAnnotationException(
Messages.UNMATCHABLE_ADAPTER.format(
nav().getTypeName(adapter), nav().getTypeName(t)),
xjta
));
}
}
} else {
adapter = new Adapter<T,C>(xjta,reader(),nav());
}
}
this.id = calcId();
+ this.schemaType = Util.calcSchemaType(reader(),seed,parent.clazz,
+ getIndividualType(),this);
}
public ClassInfoImpl<T,C,F,M> parent() {
return parent;
}
protected final Navigator<T,C,F,M> nav() {
return parent.nav();
}
protected final AnnotationReader<T,C,F,M> reader() {
return parent.reader();
}
public T getRawType() {
return seed.getRawType();
}
public T getIndividualType() {
if(adapter!=null)
return adapter.defaultType;
T raw = getRawType();
if(!isCollection()) {
return raw;
} else {
if(nav().isArrayButNotByteArray(raw))
return nav().getComponentType(raw);
T bt = nav().getBaseClass(raw, nav().asDecl(Collection.class) );
if(nav().isParameterizedType(bt))
return nav().getTypeArgument(bt,0);
else
return nav().ref(Object.class);
}
}
public final String getName() {
return seed.getName();
}
/**
* Checks if the given adapter is applicable to the declared property type.
*/
private boolean isApplicable(XmlJavaTypeAdapter jta, T declaredType ) {
if(jta==null) return false;
T type = reader().getClassValue(jta,"type");
if(declaredType.equals(type))
return true; // for types explicitly marked in XmlJavaTypeAdapter.type()
T adapter = reader().getClassValue(jta,"value");
T ba = nav().getBaseClass(adapter, nav().asDecl(XmlAdapter.class));
if(!nav().isParameterizedType(ba))
return true; // can't check type applicability. assume Object, which means applicable to any.
T inMemType = nav().getTypeArgument(ba, 1);
return nav().isSubClassOf(declaredType,inMemType);
}
private XmlJavaTypeAdapter getApplicableAdapter(T type) {
XmlJavaTypeAdapter jta = seed.readAnnotation(XmlJavaTypeAdapter.class);
if(jta!=null && isApplicable(jta,type))
return jta;
// check the applicable adapters on the package
XmlJavaTypeAdapters jtas = reader().getPackageAnnotation(XmlJavaTypeAdapters.class, parent.clazz, seed );
if(jtas!=null) {
for (XmlJavaTypeAdapter xjta : jtas.value()) {
if(isApplicable(xjta,type))
return xjta;
}
}
jta = reader().getPackageAnnotation(XmlJavaTypeAdapter.class, parent.clazz, seed );
if(isApplicable(jta,type))
return jta;
// then on the target class
C refType = nav().asDecl(type);
if(refType!=null) {
jta = reader().getClassAnnotation(XmlJavaTypeAdapter.class, refType, seed );
if(jta!=null && isApplicable(jta,type)) // the one on the type always apply.
return jta;
}
return null;
}
/**
* This is the default implementation of the getAdapter method
* defined on many of the {@link PropertyInfo}-derived classes.
*/
public Adapter<T,C> getAdapter() {
return adapter;
}
public final String displayName() {
return nav().getClassName(parent.getClazz())+'#'+getName();
}
public final ID id() {
return id;
}
private ID calcId() {
if(seed.hasAnnotation(XmlID.class)) {
// check the type
if(!getIndividualType().equals(nav().ref(String.class)))
parent.builder.reportError(new IllegalAnnotationException(
Messages.ID_MUST_BE_STRING.format(getName()), seed )
);
return ID.ID;
} else
if(seed.hasAnnotation(XmlIDREF.class)) {
return ID.IDREF;
} else {
return ID.NONE;
}
}
public final MimeType getExpectedMimeType() {
return expectedMimeType;
}
public final boolean inlineBinaryData() {
return inlineBinary;
}
public final QName getSchemaType() {
return schemaType;
}
public final boolean isCollection() {
return isCollection;
}
/**
* Called after all the {@link TypeInfo}s are collected into the governing {@link TypeInfoSet}.
*
* Derived class can do additional actions to complete the model.
*/
protected void link() {
if(id==ID.IDREF) {
// make sure that the refereced type has ID
for (TypeInfo<T,C> ti : ref()) {
if(!ti.canBeReferencedByIDREF())
parent.builder.reportError(new IllegalAnnotationException(
Messages.INVALID_IDREF.format(
parent.builder.nav.getTypeName(ti.getType())), this ));
}
}
}
/**
* A {@link PropertyInfoImpl} is always referenced by its enclosing class,
* so return that as the upstream.
*/
public Locatable getUpstream() {
return parent;
}
public Location getLocation() {
return seed.getLocation();
}
//
//
// convenience methods for derived classes
//
//
/**
* Computes the tag name from a {@link XmlElement} by taking the defaulting into account.
*/
protected final QName calcXmlName(XmlElement e) {
if(e!=null)
return calcXmlName(e.namespace(),e.name());
else
return calcXmlName("##default","##default");
}
/**
* Computes the tag name from a {@link XmlElementWrapper} by taking the defaulting into account.
*/
protected final QName calcXmlName(XmlElementWrapper e) {
if(e!=null)
return calcXmlName(e.namespace(),e.name());
else
return calcXmlName("##default","##default");
}
private QName calcXmlName(String uri,String local) {
// compute the default
TODO.checkSpec();
if(local.length()==0 || local.equals("##default"))
local = seed.getName();
if(uri.equals("##default")) {
XmlSchema xs = reader().getPackageAnnotation( XmlSchema.class, parent.getClazz(), this );
// JAX-RPC doesn't want the default namespace URI swapping to take effect to
// local "unqualified" elements. UGLY.
if(xs!=null) {
switch(xs.elementFormDefault()) {
case QUALIFIED:
QName typeName = parent.getTypeName();
if(typeName!=null)
uri = typeName.getNamespaceURI();
else
uri = xs.namespace();
if(uri.length()==0)
uri = parent.builder.defaultNsUri;
break;
case UNQUALIFIED:
case UNSET:
uri = "";
}
} else {
uri = "";
}
}
return new QName(uri.intern(),local.intern());
}
public int compareTo(PropertyInfoImpl that) {
return this.getName().compareTo(that.getName());
}
public final <A extends Annotation> A readAnnotation(Class<A> annotationType) {
return seed.readAnnotation(annotationType);
}
public final boolean hasAnnotation(Class<? extends Annotation> annotationType) {
return seed.hasAnnotation(annotationType);
}
}
| false | true | protected PropertyInfoImpl(ClassInfoImpl<T,C,F,M> parent, PropertySeed<T,C,F,M> spi) {
this.seed = spi;
this.parent = parent;
if(parent==null)
/*
Various people reported a bug where this parameter is somehow null.
In an attempt to catch the error better, let's do an explicit check here.
http://forums.java.net/jive/thread.jspa?threadID=18479
http://forums.java.net/jive/thread.jspa?messageID=165946
*/
throw new AssertionError();
MimeType mt = Util.calcExpectedMediaType(seed,parent.builder);
if(mt!=null && !kind().canHaveXmlMimeType) {
parent.builder.reportError(new IllegalAnnotationException(
Messages.ILLEGAL_ANNOTATION.format(XmlMimeType.class.getName()),
seed.readAnnotation(XmlMimeType.class)
));
mt = null;
}
this.expectedMimeType = mt;
this.inlineBinary = seed.hasAnnotation(XmlInlineBinaryData.class);
this.schemaType = Util.calcSchemaType(reader(),seed,parent.clazz,
getIndividualType(),this);
T t = seed.getRawType();
// check if there's an adapter applicable to the whole property
XmlJavaTypeAdapter xjta = getApplicableAdapter(t);
if(xjta!=null) {
isCollection = false;
adapter = new Adapter<T,C>(xjta,reader(),nav());
} else {
// check if the adapter is applicable to the individual item in the property
this.isCollection = nav().isSubClassOf(t, nav().ref(Collection.class))
|| nav().isArrayButNotByteArray(t);
xjta = getApplicableAdapter(getIndividualType());
if(xjta==null) {
// ugly ugly hack, but we implement swaRef as adapter
XmlAttachmentRef xsa = seed.readAnnotation(XmlAttachmentRef.class);
if(xsa!=null) {
parent.builder.hasSwaRef = true;
adapter = new Adapter<T,C>(nav().asDecl(SwaRefAdapter.class),nav());
} else {
adapter = null;
// if this field has adapter annotation but not applicable,
// that must be an error of the user
xjta = seed.readAnnotation(XmlJavaTypeAdapter.class);
if(xjta!=null) {
T adapter = reader().getClassValue(xjta,"value");
parent.builder.reportError(new IllegalAnnotationException(
Messages.UNMATCHABLE_ADAPTER.format(
nav().getTypeName(adapter), nav().getTypeName(t)),
xjta
));
}
}
} else {
adapter = new Adapter<T,C>(xjta,reader(),nav());
}
}
this.id = calcId();
}
| protected PropertyInfoImpl(ClassInfoImpl<T,C,F,M> parent, PropertySeed<T,C,F,M> spi) {
this.seed = spi;
this.parent = parent;
if(parent==null)
/*
Various people reported a bug where this parameter is somehow null.
In an attempt to catch the error better, let's do an explicit check here.
http://forums.java.net/jive/thread.jspa?threadID=18479
http://forums.java.net/jive/thread.jspa?messageID=165946
*/
throw new AssertionError();
MimeType mt = Util.calcExpectedMediaType(seed,parent.builder);
if(mt!=null && !kind().canHaveXmlMimeType) {
parent.builder.reportError(new IllegalAnnotationException(
Messages.ILLEGAL_ANNOTATION.format(XmlMimeType.class.getName()),
seed.readAnnotation(XmlMimeType.class)
));
mt = null;
}
this.expectedMimeType = mt;
this.inlineBinary = seed.hasAnnotation(XmlInlineBinaryData.class);
T t = seed.getRawType();
// check if there's an adapter applicable to the whole property
XmlJavaTypeAdapter xjta = getApplicableAdapter(t);
if(xjta!=null) {
isCollection = false;
adapter = new Adapter<T,C>(xjta,reader(),nav());
} else {
// check if the adapter is applicable to the individual item in the property
this.isCollection = nav().isSubClassOf(t, nav().ref(Collection.class))
|| nav().isArrayButNotByteArray(t);
xjta = getApplicableAdapter(getIndividualType());
if(xjta==null) {
// ugly ugly hack, but we implement swaRef as adapter
XmlAttachmentRef xsa = seed.readAnnotation(XmlAttachmentRef.class);
if(xsa!=null) {
parent.builder.hasSwaRef = true;
adapter = new Adapter<T,C>(nav().asDecl(SwaRefAdapter.class),nav());
} else {
adapter = null;
// if this field has adapter annotation but not applicable,
// that must be an error of the user
xjta = seed.readAnnotation(XmlJavaTypeAdapter.class);
if(xjta!=null) {
T adapter = reader().getClassValue(xjta,"value");
parent.builder.reportError(new IllegalAnnotationException(
Messages.UNMATCHABLE_ADAPTER.format(
nav().getTypeName(adapter), nav().getTypeName(t)),
xjta
));
}
}
} else {
adapter = new Adapter<T,C>(xjta,reader(),nav());
}
}
this.id = calcId();
this.schemaType = Util.calcSchemaType(reader(),seed,parent.clazz,
getIndividualType(),this);
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/helper/AccessPointHelper.java b/GAE/src/org/waterforpeople/mapping/helper/AccessPointHelper.java
index 4d938cced..5609a96bc 100644
--- a/GAE/src/org/waterforpeople/mapping/helper/AccessPointHelper.java
+++ b/GAE/src/org/waterforpeople/mapping/helper/AccessPointHelper.java
@@ -1,779 +1,781 @@
package org.waterforpeople.mapping.helper;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.dao.AccessPointDao;
import org.waterforpeople.mapping.dao.AccessPointScoreDetailDao;
import org.waterforpeople.mapping.dao.SurveyAttributeMappingDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPointMappingHistory;
import org.waterforpeople.mapping.domain.AccessPointScoreDetail;
import org.waterforpeople.mapping.domain.GeoCoordinates;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyAttributeMapping;
import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.gallatinsystems.common.util.StringUtil;
import com.gallatinsystems.framework.analytics.summarization.DataSummarizationRequest;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.framework.domain.DataChangeRecord;
import com.gallatinsystems.gis.location.GeoLocationServiceGeonamesImpl;
import com.gallatinsystems.gis.location.GeoPlace;
import com.gallatinsystems.gis.map.domain.OGRFeature;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.domain.Question;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
public class AccessPointHelper {
private static String photo_url_root;
private static final String GEO_TYPE = "GEO";
private static final String PHOTO_TYPE = "IMAGE";
private SurveyAttributeMappingDao mappingDao;
static {
Properties props = System.getProperties();
photo_url_root = props.getProperty("photo_url_root");
}
private static Logger logger = Logger.getLogger(AccessPointHelper.class
.getName());
public AccessPointHelper() {
mappingDao = new SurveyAttributeMappingDao();
}
public AccessPoint getAccessPoint(Long id) {
BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class);
return apDAO.getByKey(id);
}
public AccessPoint getAccessPoint(Long id, Boolean needScoreDetail) {
BaseDAO<AccessPoint> apDAO = new BaseDAO<AccessPoint>(AccessPoint.class);
AccessPointScoreDetailDao apddao = new AccessPointScoreDetailDao();
AccessPoint ap = apDAO.getByKey(id);
List<AccessPointScoreDetail> apScoreSummaryList = apddao
.listByAccessPointId(id);
if (apScoreSummaryList != null && !apScoreSummaryList.isEmpty())
ap.setApScoreDetailList(apScoreSummaryList);
return ap;
}
public void processSurveyInstance(String surveyInstanceId) {
// Get the survey and QuestionAnswerStore
// Get the surveyDefinition
SurveyInstanceDAO sid = new SurveyInstanceDAO();
List<QuestionAnswerStore> questionAnswerList = sid
.listQuestionAnswerStore(Long.parseLong(surveyInstanceId), null);
Collection<AccessPoint> apList = null;
if (questionAnswerList != null && questionAnswerList.size() > 0) {
try {
apList = parseAccessPoint(new Long(questionAnswerList.get(0)
.getSurveyId()), questionAnswerList,
AccessPoint.AccessPointType.WATER_POINT);
} catch (Exception ex) {
logger.log(Level.SEVERE, "problem parsing access point." + ex);
}
if (apList != null) {
for (AccessPoint ap : apList) {
try {
saveAccessPoint(ap);
} catch (Exception ex) {
logger.log(
Level.SEVERE,
"Inside processSurveyInstance could not save AP for SurveyInstanceId: "
+ surveyInstanceId + ":"
+ ap.toString() + " ex: " + ex
+ " exMessage: " + ex.getMessage());
}
}
}
}
}
private Collection<AccessPoint> parseAccessPoint(Long surveyId,
List<QuestionAnswerStore> questionAnswerList,
AccessPoint.AccessPointType accessPointType) {
Collection<AccessPoint> apList = null;
List<SurveyAttributeMapping> mappings = mappingDao
.listMappingsBySurvey(surveyId);
if (mappings != null) {
apList = parseAccessPoint(surveyId, questionAnswerList, mappings);
} else {
logger.log(Level.SEVERE, "NO mappings for survey " + surveyId);
}
return apList;
}
/**
* uses the saved mappings for the survey definition to parse values in the
* questionAnswerStore into attributes of an AccessPoint object
*
* TODO: figure out way around known limitation of only having 1 GEO
* response per survey
*
* @param questionAnswerList
* @param mappings
* @return
*/
private Collection<AccessPoint> parseAccessPoint(Long surveyId,
List<QuestionAnswerStore> questionAnswerList,
List<SurveyAttributeMapping> mappings) {
HashMap<String, AccessPoint> apMap = new HashMap<String, AccessPoint>();
List<AccessPointMappingHistory> apmhList = new ArrayList<AccessPointMappingHistory>();
List<Question> questionList = new QuestionDao()
.listQuestionsBySurvey(surveyId);
if (questionAnswerList != null) {
for (QuestionAnswerStore qas : questionAnswerList) {
SurveyAttributeMapping mapping = getMappingForQuestion(
mappings, qas.getQuestionID());
if (mapping != null) {
List<String> types = mapping.getApTypes();
if (types == null || types.size() == 0) {
// default the list to be access point if nothing is
// specified (for backward compatibility)
types.add(AccessPointType.WATER_POINT.toString());
} else {
if (types.contains(AccessPointType.PUBLIC_INSTITUTION
.toString())
&& (types.contains(AccessPointType.HEALTH_POSTS
.toString()) || types
.contains(AccessPointType.SCHOOL
.toString()))) {
types.remove(AccessPointType.PUBLIC_INSTITUTION
.toString());
}
}
for (String type : types) {
AccessPointMappingHistory apmh = new AccessPointMappingHistory();
apmh.setSource(this.getClass().getName());
apmh.setSurveyId(surveyId);
apmh.setSurveyInstanceId(qas.getSurveyInstanceId());
apmh.setQuestionId(Long.parseLong(qas.getQuestionID()));
apmh.addAccessPointType(type);
try {
AccessPoint ap = apMap.get(type);
if (ap == null) {
ap = new AccessPoint();
ap.setPointType(AccessPointType.valueOf(type));
// if(AccessPointType.PUBLIC_INSTITUTION.toString().equals(type)){
// //get the pointType value from the survey to
// properly set it
//
// }
apMap.put(type, ap);
}
ap.setCollectionDate(qas.getCollectionDate());
setAccessPointField(ap, qas, mapping, apmh);
} catch (NoSuchFieldException e) {
logger.log(
Level.SEVERE,
"Could not map field to access point: "
+ mapping.getAttributeName()
+ ". Check the surveyAttribueMapping for surveyId "
+ surveyId);
} catch (IllegalAccessException e) {
logger.log(Level.SEVERE,
"Could not set field to access point: "
+ mapping.getAttributeName()
+ ". Illegal access.");
}
for (Question q : questionList) {
if (q.getKey().getId() == Long.parseLong(qas
.getQuestionID())) {
apmh.setQuestionText(q.getText());
break;
}
}
apmhList.add(apmh);
}
}
// if (apmhList.size() > 0) {
// BaseDAO<AccessPointMappingHistory> apmhDao = new
// BaseDAO<AccessPointMappingHistory>(
// AccessPointMappingHistory.class);
// apmhDao.save(apmhList);
// }
}
}
return apMap.values();
}
/**
* uses reflection to set the field on access point based on the value in
* questionAnswerStore and the field name in the mapping
*
* @param ap
* @param qas
* @param mapping
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setAccessPointField(AccessPoint ap,
QuestionAnswerStore qas, SurveyAttributeMapping mapping,
AccessPointMappingHistory apmh) throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
apmh.setResponseAnswerType(qas.getType());
QuestionDao qDao = new QuestionDao();
ap.setSurveyId(qas.getSurveyId());
ap.setSurveyInstanceId(qas.getSurveyInstanceId());
Question q = qDao.getByKey(Long.parseLong(qas.getQuestionID()));
- if (!qas.getType().equals(q.getType().toString())){
+ if (!qas.getType().equals(q.getType().toString())) {
qas.setType(q.getType().toString());
- logger.log(Level.INFO,"Remapping question type value because QAS version is incorrect");
+ logger.log(Level.INFO,
+ "Remapping question type value because QAS version is incorrect");
}
- //FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME, STRENGTH
+ // FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME,
+ // STRENGTH
- if (GEO_TYPE.equals(q.getType())) {
+ if (GEO_TYPE.equals(q.getType().toString())) {
GeoCoordinates geoC = new GeoCoordinates().extractGeoCoordinate(qas
.getValue());
ap.setLatitude(geoC.getLatitude());
ap.setLongitude(geoC.getLongitude());
ap.setAltitude(geoC.getAltitude());
if (ap.getCommunityCode() == null && geoC.getCode() != null) {
ap.setCommunityCode(geoC.getCode());
}
apmh.setSurveyResponse(geoC.getLatitude() + "|"
+ geoC.getLongitude() + "|" + geoC.getAltitude());
apmh.setQuestionAnswerType("GEO");
apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude()
+ "|" + ap.getAltitude());
apmh.setAccessPointField("Latitude,Longitude,Altitude");
} else {
apmh.setSurveyResponse(qas.getValue());
// if it's a value or OTHER type
Field f = ap.getClass()
.getDeclaredField(mapping.getAttributeName());
if (!f.isAccessible()) {
f.setAccessible(true);
}
apmh.setAccessPointField(f.getName());
// TODO: Hack. In the QAS the type is PHOTO, but we were looking for
// image this is why we were getting /sdcard I think.
- if (PHOTO_TYPE.equals(q.getType())
+ if (PHOTO_TYPE.equals(q.getType().toString())
|| qas.getType().equals("PHOTO")) {
String newURL = null;
String[] photoParts = qas.getValue().split("/");
if (qas.getValue().startsWith("/sdcard")) {
newURL = photo_url_root + photoParts[2];
} else if (qas.getValue().startsWith("/mnt")) {
newURL = photo_url_root + photoParts[3];
}
f.set(ap, newURL);
apmh.setQuestionAnswerType("PHOTO");
apmh.setAccessPointValue(ap.getPhotoURL());
} else if (mapping.getAttributeName().equals("pointType")) {
if (qas.getValue().contains("Health")) {
f.set(ap, AccessPointType.HEALTH_POSTS);
} else {
qas.setValue(qas.getValue().replace(" ", "_"));
f.set(ap, AccessPointType.valueOf(qas.getValue()
.toUpperCase()));
}
} else {
String stringVal = qas.getValue();
if (stringVal != null && stringVal.trim().length() > 0) {
if (f.getType() == String.class) {
f.set(ap, qas.getValue());
apmh.setQuestionAnswerType("String");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == AccessPoint.Status.class) {
String val = qas.getValue();
f.set(ap, encodeStatus(val, ap.getPointType()));
apmh.setQuestionAnswerType("STATUS");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == Double.class) {
try {
Double val = Double.parseDouble(stringVal.trim());
f.set(ap, val);
apmh.setQuestionAnswerType("DOUBLE");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as double", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as double");
}
} else if (f.getType() == Long.class) {
try {
String temp = stringVal.trim();
if (temp.contains(".")) {
temp = temp.substring(0, temp.indexOf("."));
}
Long val = Long.parseLong(temp);
f.set(ap, val);
logger.info("Setting "
+ f.getName()
+ " to "
+ val
+ " for ap: "
+ (ap.getKey() != null ? ap.getKey()
.getId() : "UNSET"));
apmh.setQuestionAnswerType("LONG");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as long", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as long");
}
} else if (f.getType() == Boolean.class) {
try {
Boolean val = null;
if (stringVal.toLowerCase().contains("yes")) {
val = true;
} else if (stringVal.toLowerCase().contains("no")) {
val = false;
} else {
if (stringVal == null || stringVal.equals("")) {
val = null;
}
val = Boolean.parseBoolean(stringVal.trim());
}
f.set(ap, val);
apmh.setQuestionAnswerType("BOOLEAN");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as boolean", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as boolean");
}
}
}
}
}
}
/**
* reads value of field from AccessPoint via reflection
*
* @param ap
* @param field
* @return
*/
public static String getAccessPointFieldAsString(AccessPoint ap,
String field) {
try {
Field f = ap.getClass().getDeclaredField(field);
if (!f.isAccessible()) {
f.setAccessible(true);
}
Object val = f.get(ap);
if (val != null) {
return val.toString();
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not extract field value: " + field,
e);
}
return null;
}
private SurveyAttributeMapping getMappingForQuestion(
List<SurveyAttributeMapping> mappings, String questionId) {
if (mappings != null) {
for (SurveyAttributeMapping mapping : mappings) {
if (mapping.getSurveyQuestionId().equals(questionId)) {
return mapping;
}
}
}
return null;
}
/**
* generates a unique code based on the lat/lon passed in. Current algorithm
* returns the concatenation of the integer portion of 1000 times absolute
*
* value of lat and lon in base 36
*
* @param lat
* @param lon
* @return
*/
private String generateCode(double lat, double lon) {
Long code = Long.parseLong((int) ((Math.abs(lat) * 10000d)) + ""
+ (int) ((Math.abs(lon) * 10000d)));
return Long.toString(code, 36);
}
/**
* saves an access point and fires off a summarization message
*
* @param ap
* @return
*/
public AccessPoint saveAccessPoint(AccessPoint ap) {
AccessPointDao apDao = new AccessPointDao();
AccessPoint apCurrent = null;
if (ap != null) {
if (ap.getPointType() != null && ap.getLatitude() != null
&& ap.getLongitude() != null) {
apCurrent = apDao.findAccessPoint(ap.getPointType(),
ap.getLatitude(), ap.getLongitude(),
ap.getCollectionDate());
if (apCurrent != null) {
// if (!apCurrent.getKey().equals(ap.getKey())) {
ap.setKey(apCurrent.getKey());
// }
}
if (ap.getAccessPointCode() == null) {
ap.setAccessPointCode(generateCode(ap.getLatitude(),
ap.getLongitude()));
logger.log(
Level.INFO,
"No APCode set in ap so setting to: "
+ ap.getAccessPointCode());
}
if (ap.getCommunityCode() == null) {
if (ap.getAccessPointCode() != null)
ap.setCommunityCode(ap.getAccessPointCode());
logger.log(
Level.INFO,
"No Community Code set in ap so setting to: "
+ ap.getAccessPointCode());
}
if (ap.getKey() != null) {
String oldValues = null;
if (ap != null && ap.getKey() != null && apCurrent == null) {
apCurrent = apDao.getByKey(ap.getKey());
}
if (apCurrent != null) {
oldValues = formChangeRecordString(apCurrent);
if (apCurrent != null) {
ap.setKey(apCurrent.getKey());
apCurrent = ap;
logger.log(Level.INFO,
"Found existing point and updating it."
+ apCurrent.getKey().getId());
}
// TODO: Hack since the fileUrl keeps getting set to
// incorrect value
// Changing from apCurrent to ap
ap = apDao.save(ap);
String newValues = formChangeRecordString(ap);
if (oldValues != null) {
DataChangeRecord change = new DataChangeRecord(
AccessPointStatusSummary.class.getName(),
"n/a", oldValues, newValues);
Queue queue = QueueFactory.getQueue("dataUpdate");
queue.add(url("/app_worker/dataupdate")
.param(DataSummarizationRequest.OBJECT_KEY,
ap.getKey().getId() + "")
.param(DataSummarizationRequest.OBJECT_TYPE,
"AccessPointSummaryChange")
.param(DataSummarizationRequest.VALUE_KEY,
change.packString()));
}
}
} else {
logger.log(Level.INFO,
"Did not find existing point" + ap.toString());
if (ap.getGeocells() == null
|| ap.getGeocells().size() == 0) {
if (ap.getLatitude() != null
&& ap.getLongitude() != null
&& ap.getLongitude() < 180
&& ap.getLatitude() < 180) {
try {
ap.setGeocells(GeocellManager
.generateGeoCell(new Point(ap
.getLatitude(), ap
.getLongitude())));
} catch (Exception ex) {
logger.log(Level.INFO,
"Could not generate GeoCell for AP: "
+ ap.getKey().getId()
+ " error: " + ex);
}
}
}
try {
ap = apDao.save(ap);
} catch (Exception ex) {
logger.log(Level.INFO, "Could not save point");
}
if (ap.getKey() != null) {
Queue summQueue = QueueFactory
.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization")
.param("objectKey", ap.getKey().getId() + "")
.param("type", "AccessPoint"));
} else {
logger.log(
Level.SEVERE,
"After saving could not get key"
+ ap.toString());
}
}
}
}
if (ap != null) {
return ap;
} else
return null;
}
private String formChangeRecordString(AccessPoint ap) {
String changeString = null;
if (ap != null) {
changeString = (ap.getCountryCode() != null ? ap.getCountryCode()
: "")
+ "|"
+ (ap.getCommunityCode() != null ? ap.getCommunityCode()
: "")
+ "|"
+ (ap.getPointType() != null ? ap.getPointType().toString()
: "")
+ "|"
+ (ap.getPointStatus() != null ? ap.getPointStatus()
.toString() : "")
+ "|"
+ StringUtil.getYearString(ap.getCollectionDate());
}
return changeString;
}
public List<AccessPoint> listAccessPoint(String cursorString) {
AccessPointDao apDao = new AccessPointDao();
return apDao.list(cursorString);
}
public static AccessPoint.Status encodeStatus(String statusVal,
AccessPoint.AccessPointType pointType) {
AccessPoint.Status status = null;
statusVal = statusVal.toLowerCase().trim();
if (pointType.equals(AccessPointType.WATER_POINT)) {
if ("functioning but with problems".equals(statusVal)
|| "working but with problems".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
} else if ("broken down system".equals(statusVal)
|| "broken down".equals(statusVal)
|| statusVal.contains("broken")) {
status = AccessPoint.Status.BROKEN_DOWN;
} else if ("no improved system".equals(statusVal)
|| "not a protected waterpoint".equals(statusVal)) {
status = AccessPoint.Status.NO_IMPROVED_SYSTEM;
} else if ("functioning and meets government standards"
.equals(statusVal)
|| "working and protected".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("high".equalsIgnoreCase(statusVal)
|| "functioning".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("ok".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_OK;
} else {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
}
} else if (pointType.equals(AccessPointType.SANITATION_POINT)) {
if ("latrine full".equals(statusVal))
status = AccessPoint.Status.LATRINE_FULL;
else if ("Latrine used but technical problems evident"
.toLowerCase().trim().equals(statusVal))
status = AccessPoint.Status.LATRINE_USED_TECH_PROBLEMS;
else if ("Latrine not being used due to structural/technical problems"
.toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_NOT_USED_TECH_STRUCT_PROBLEMS;
else if ("Do not Know".toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_DO_NOT_KNOW;
else if ("Functional".toLowerCase().equals(statusVal))
status = AccessPoint.Status.LATRINE_FUNCTIONAL;
} else {
if ("functioning but with problems".equals(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
} else if ("broken down system".equals(statusVal)) {
status = AccessPoint.Status.BROKEN_DOWN;
} else if ("no improved system".equals(statusVal))
status = AccessPoint.Status.NO_IMPROVED_SYSTEM;
else if ("functioning and meets government standards"
.equals(statusVal))
status = AccessPoint.Status.FUNCTIONING_HIGH;
else if ("high".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_HIGH;
} else if ("ok".equalsIgnoreCase(statusVal)) {
status = AccessPoint.Status.FUNCTIONING_OK;
} else {
status = AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS;
}
}
return status;
}
private void copyNonKeyValues(AccessPoint source, AccessPoint target) {
if (source != null && target != null) {
Field[] fields = AccessPoint.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
try {
if (isCopyable(fields[i].getName())) {
fields[i].setAccessible(true);
fields[i].set(target, fields[i].get(source));
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Can't set the field: "
+ fields[i].getName());
}
}
}
}
private boolean isCopyable(String name) {
if ("key".equals(name)) {
return false;
} else if ("serialVersionUID".equals(name)) {
return false;
} else if ("jdoFieldFlags".equals(name)) {
return false;
} else if ("jdoPersistenceCapableSuperclass".equals(name)) {
return false;
} else if ("jdoFieldTypes".equals(name)) {
return false;
} else if ("jdoFieldNames".equals(name)) {
return false;
} else if ("jdoInheritedFieldCount".equals(name)) {
return false;
}
return true;
}
public AccessPoint setGeoDetails(AccessPoint point) {
if (point.getLatitude() != null && point.getLongitude() != null) {
GeoLocationServiceGeonamesImpl gs = new GeoLocationServiceGeonamesImpl();
GeoPlace geoPlace = gs.manualLookup(point.getLatitude().toString(),
point.getLongitude().toString(),
OGRFeature.FeatureType.SUB_COUNTRY_OTHER);
if (geoPlace != null) {
point.setCountryCode(geoPlace.getCountryCode());
point.setSub1(geoPlace.getSub1());
point.setSub2(geoPlace.getSub2());
point.setSub3(geoPlace.getSub3());
point.setSub4(geoPlace.getSub4());
point.setSub5(geoPlace.getSub5());
point.setSub6(geoPlace.getSub6());
} else if (geoPlace == null && point.getCountryCode() == null) {
GeoPlace geoPlaceCountry = gs.manualLookup(point.getLatitude()
.toString(), point.getLongitude().toString(),
OGRFeature.FeatureType.COUNTRY);
if (geoPlaceCountry != null) {
point.setCountryCode(geoPlaceCountry.getCountryCode());
}
}
}
return point;
}
public static AccessPoint scoreAccessPoint(AccessPoint ap) {
// Is there an improved water system no=0, yes=1
// Provide enough drinking water for community everyday of year no=0,
// yes=1, don't know=0,
// Water system been down in 30 days: No=1,yes=0
// Are there current problems: no=1,yes=0
// meet govt quantity standards:no=0,yes=1
// Is there a tarriff or fee no=0,yes=1
AccessPointScoreDetail apss = new AccessPointScoreDetail();
logger.log(Level.INFO,
"About to compute score for: " + ap.getCommunityCode());
Integer score = 0;
if (ap.isImprovedWaterPointFlag() != null
&& ap.isImprovedWaterPointFlag()) {
score++;
apss.addScoreComputationItem("Plus 1 for Improved Water System = true: ");
if (ap.getProvideAdequateQuantity() != null
&& ap.getProvideAdequateQuantity().equals(true)) {
score++;
apss.addScoreComputationItem("Plus 1 for Provide Adequate Quantity = true: ");
} else {
apss.addScoreComputationItem("Plus 0 for Provide Adequate Quantity = false or null: ");
}
if (ap.getHasSystemBeenDown1DayFlag() != null
&& !ap.getHasSystemBeenDown1DayFlag().equals(true)) {
score++;
apss.addScoreComputationItem("Plus 1 for Has System Been Down 1 Day Flag = false: ");
} else {
apss.addScoreComputationItem("Plus 0 for Has System Been Down 1 Day Flag = true or null: ");
}
if (ap.getCurrentProblem() == null) {
score++;
apss.addScoreComputationItem("Plus 1 for Get Current Problem = null");
} else {
apss.addScoreComputationItem("Plus 0 for Get Current Problem != null value: "
+ ap.getCurrentProblem());
}
if (ap.isCollectTariffFlag() != null && ap.isCollectTariffFlag()) {
score++;
apss.addScoreComputationItem("Plus 1 for Collect Tariff Flag = true ");
} else {
apss.addScoreComputationItem("Plus 0 for Collect Tariff Flag = false or null: ");
}
} else {
apss.addScoreComputationItem("Plus 0 for Improved Water System = false or null: ");
}
apss.setScore(score);
ap.setScore(score);
ap.setScoreComputationDate(new Date());
apss.setComputationDate(ap.getScoreComputationDate());
logger.log(Level.INFO,
"AP Collected in 2011 so scoring: " + ap.getCommunityCode()
+ "/" + ap.getCollectionDate() + " score: " + score);
if (score == 0) {
ap.setPointStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM);
apss.setStatus(AccessPoint.Status.NO_IMPROVED_SYSTEM.toString());
} else if (score >= 1 && score <= 2) {
ap.setPointStatus(AccessPoint.Status.BROKEN_DOWN);
apss.setStatus(AccessPoint.Status.BROKEN_DOWN.toString());
} else if (score >= 3 && score <= 4) {
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS);
apss.setStatus(AccessPoint.Status.FUNCTIONING_WITH_PROBLEMS
.toString());
} else if (score >= 5) {
ap.setPointStatus(AccessPoint.Status.FUNCTIONING_HIGH);
apss.setStatus(AccessPoint.Status.FUNCTIONING_HIGH.toString());
} else {
ap.setPointStatus(AccessPoint.Status.OTHER);
apss.setStatus(AccessPoint.Status.OTHER.toString());
}
ap.setApScoreDetail(apss);
return ap;
}
}
| false | true | public static void setAccessPointField(AccessPoint ap,
QuestionAnswerStore qas, SurveyAttributeMapping mapping,
AccessPointMappingHistory apmh) throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
apmh.setResponseAnswerType(qas.getType());
QuestionDao qDao = new QuestionDao();
ap.setSurveyId(qas.getSurveyId());
ap.setSurveyInstanceId(qas.getSurveyInstanceId());
Question q = qDao.getByKey(Long.parseLong(qas.getQuestionID()));
if (!qas.getType().equals(q.getType().toString())){
qas.setType(q.getType().toString());
logger.log(Level.INFO,"Remapping question type value because QAS version is incorrect");
}
//FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME, STRENGTH
if (GEO_TYPE.equals(q.getType())) {
GeoCoordinates geoC = new GeoCoordinates().extractGeoCoordinate(qas
.getValue());
ap.setLatitude(geoC.getLatitude());
ap.setLongitude(geoC.getLongitude());
ap.setAltitude(geoC.getAltitude());
if (ap.getCommunityCode() == null && geoC.getCode() != null) {
ap.setCommunityCode(geoC.getCode());
}
apmh.setSurveyResponse(geoC.getLatitude() + "|"
+ geoC.getLongitude() + "|" + geoC.getAltitude());
apmh.setQuestionAnswerType("GEO");
apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude()
+ "|" + ap.getAltitude());
apmh.setAccessPointField("Latitude,Longitude,Altitude");
} else {
apmh.setSurveyResponse(qas.getValue());
// if it's a value or OTHER type
Field f = ap.getClass()
.getDeclaredField(mapping.getAttributeName());
if (!f.isAccessible()) {
f.setAccessible(true);
}
apmh.setAccessPointField(f.getName());
// TODO: Hack. In the QAS the type is PHOTO, but we were looking for
// image this is why we were getting /sdcard I think.
if (PHOTO_TYPE.equals(q.getType())
|| qas.getType().equals("PHOTO")) {
String newURL = null;
String[] photoParts = qas.getValue().split("/");
if (qas.getValue().startsWith("/sdcard")) {
newURL = photo_url_root + photoParts[2];
} else if (qas.getValue().startsWith("/mnt")) {
newURL = photo_url_root + photoParts[3];
}
f.set(ap, newURL);
apmh.setQuestionAnswerType("PHOTO");
apmh.setAccessPointValue(ap.getPhotoURL());
} else if (mapping.getAttributeName().equals("pointType")) {
if (qas.getValue().contains("Health")) {
f.set(ap, AccessPointType.HEALTH_POSTS);
} else {
qas.setValue(qas.getValue().replace(" ", "_"));
f.set(ap, AccessPointType.valueOf(qas.getValue()
.toUpperCase()));
}
} else {
String stringVal = qas.getValue();
if (stringVal != null && stringVal.trim().length() > 0) {
if (f.getType() == String.class) {
f.set(ap, qas.getValue());
apmh.setQuestionAnswerType("String");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == AccessPoint.Status.class) {
String val = qas.getValue();
f.set(ap, encodeStatus(val, ap.getPointType()));
apmh.setQuestionAnswerType("STATUS");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == Double.class) {
try {
Double val = Double.parseDouble(stringVal.trim());
f.set(ap, val);
apmh.setQuestionAnswerType("DOUBLE");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as double", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as double");
}
} else if (f.getType() == Long.class) {
try {
String temp = stringVal.trim();
if (temp.contains(".")) {
temp = temp.substring(0, temp.indexOf("."));
}
Long val = Long.parseLong(temp);
f.set(ap, val);
logger.info("Setting "
+ f.getName()
+ " to "
+ val
+ " for ap: "
+ (ap.getKey() != null ? ap.getKey()
.getId() : "UNSET"));
apmh.setQuestionAnswerType("LONG");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as long", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as long");
}
} else if (f.getType() == Boolean.class) {
try {
Boolean val = null;
if (stringVal.toLowerCase().contains("yes")) {
val = true;
} else if (stringVal.toLowerCase().contains("no")) {
val = false;
} else {
if (stringVal == null || stringVal.equals("")) {
val = null;
}
val = Boolean.parseBoolean(stringVal.trim());
}
f.set(ap, val);
apmh.setQuestionAnswerType("BOOLEAN");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as boolean", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as boolean");
}
}
}
}
}
}
| public static void setAccessPointField(AccessPoint ap,
QuestionAnswerStore qas, SurveyAttributeMapping mapping,
AccessPointMappingHistory apmh) throws SecurityException,
NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
apmh.setResponseAnswerType(qas.getType());
QuestionDao qDao = new QuestionDao();
ap.setSurveyId(qas.getSurveyId());
ap.setSurveyInstanceId(qas.getSurveyInstanceId());
Question q = qDao.getByKey(Long.parseLong(qas.getQuestionID()));
if (!qas.getType().equals(q.getType().toString())) {
qas.setType(q.getType().toString());
logger.log(Level.INFO,
"Remapping question type value because QAS version is incorrect");
}
// FREE_TEXT, OPTION, NUMBER, GEO, PHOTO, VIDEO, SCAN, TRACK, NAME,
// STRENGTH
if (GEO_TYPE.equals(q.getType().toString())) {
GeoCoordinates geoC = new GeoCoordinates().extractGeoCoordinate(qas
.getValue());
ap.setLatitude(geoC.getLatitude());
ap.setLongitude(geoC.getLongitude());
ap.setAltitude(geoC.getAltitude());
if (ap.getCommunityCode() == null && geoC.getCode() != null) {
ap.setCommunityCode(geoC.getCode());
}
apmh.setSurveyResponse(geoC.getLatitude() + "|"
+ geoC.getLongitude() + "|" + geoC.getAltitude());
apmh.setQuestionAnswerType("GEO");
apmh.setAccessPointValue(ap.getLatitude() + "|" + ap.getLongitude()
+ "|" + ap.getAltitude());
apmh.setAccessPointField("Latitude,Longitude,Altitude");
} else {
apmh.setSurveyResponse(qas.getValue());
// if it's a value or OTHER type
Field f = ap.getClass()
.getDeclaredField(mapping.getAttributeName());
if (!f.isAccessible()) {
f.setAccessible(true);
}
apmh.setAccessPointField(f.getName());
// TODO: Hack. In the QAS the type is PHOTO, but we were looking for
// image this is why we were getting /sdcard I think.
if (PHOTO_TYPE.equals(q.getType().toString())
|| qas.getType().equals("PHOTO")) {
String newURL = null;
String[] photoParts = qas.getValue().split("/");
if (qas.getValue().startsWith("/sdcard")) {
newURL = photo_url_root + photoParts[2];
} else if (qas.getValue().startsWith("/mnt")) {
newURL = photo_url_root + photoParts[3];
}
f.set(ap, newURL);
apmh.setQuestionAnswerType("PHOTO");
apmh.setAccessPointValue(ap.getPhotoURL());
} else if (mapping.getAttributeName().equals("pointType")) {
if (qas.getValue().contains("Health")) {
f.set(ap, AccessPointType.HEALTH_POSTS);
} else {
qas.setValue(qas.getValue().replace(" ", "_"));
f.set(ap, AccessPointType.valueOf(qas.getValue()
.toUpperCase()));
}
} else {
String stringVal = qas.getValue();
if (stringVal != null && stringVal.trim().length() > 0) {
if (f.getType() == String.class) {
f.set(ap, qas.getValue());
apmh.setQuestionAnswerType("String");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == AccessPoint.Status.class) {
String val = qas.getValue();
f.set(ap, encodeStatus(val, ap.getPointType()));
apmh.setQuestionAnswerType("STATUS");
apmh.setAccessPointValue(f.get(ap).toString());
} else if (f.getType() == Double.class) {
try {
Double val = Double.parseDouble(stringVal.trim());
f.set(ap, val);
apmh.setQuestionAnswerType("DOUBLE");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as double", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as double");
}
} else if (f.getType() == Long.class) {
try {
String temp = stringVal.trim();
if (temp.contains(".")) {
temp = temp.substring(0, temp.indexOf("."));
}
Long val = Long.parseLong(temp);
f.set(ap, val);
logger.info("Setting "
+ f.getName()
+ " to "
+ val
+ " for ap: "
+ (ap.getKey() != null ? ap.getKey()
.getId() : "UNSET"));
apmh.setQuestionAnswerType("LONG");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as long", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as long");
}
} else if (f.getType() == Boolean.class) {
try {
Boolean val = null;
if (stringVal.toLowerCase().contains("yes")) {
val = true;
} else if (stringVal.toLowerCase().contains("no")) {
val = false;
} else {
if (stringVal == null || stringVal.equals("")) {
val = null;
}
val = Boolean.parseBoolean(stringVal.trim());
}
f.set(ap, val);
apmh.setQuestionAnswerType("BOOLEAN");
apmh.setAccessPointValue(f.get(ap).toString());
} catch (Exception e) {
logger.log(Level.SEVERE, "Could not parse "
+ stringVal + " as boolean", e);
apmh.setMappingMessage("Could not parse "
+ stringVal + " as boolean");
}
}
}
}
}
}
|
diff --git a/src/com/urhola/cheddar/connection/Connection.java b/src/com/urhola/cheddar/connection/Connection.java
index b2dafbc..e2fa9e1 100644
--- a/src/com/urhola/cheddar/connection/Connection.java
+++ b/src/com/urhola/cheddar/connection/Connection.java
@@ -1,49 +1,41 @@
package com.urhola.cheddar.connection;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* @author janikoskela
*/
final public class Connection {
private final static int TIME_OUT_LENGTH = 2000;
private final static int HTTP_STATUS_OK = 200;
public static String sendRequest(String url) throws IOException {
- HttpURLConnection urlConnection = null;
- String out = null;
- try {
- URL u = new URL(url);
- urlConnection = (HttpURLConnection) u.openConnection();
- urlConnection.setReadTimeout(TIME_OUT_LENGTH);
- if (urlConnection.getResponseCode() != HTTP_STATUS_OK)
- return null;
- InputStream in = new BufferedInputStream(urlConnection.getInputStream());
- out = Connection.readStream(in);
- } catch(IOException e) {
- throw new IOException();
- }
- finally {
- urlConnection.disconnect();
- }
+ URL u = new URL(url);
+ HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
+ urlConnection.setReadTimeout(TIME_OUT_LENGTH);
+ if (urlConnection.getResponseCode() != HTTP_STATUS_OK)
+ throw new IOException();
+ InputStream in = new BufferedInputStream(urlConnection.getInputStream());
+ String out = Connection.readStream(in);
+ urlConnection.disconnect();
return out;
}
private static String readStream(InputStream in) throws IOException {
String line;
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
while((line = r.readLine()) != null)
sb.append(line);
return sb.toString();
}
}
| true | true | public static String sendRequest(String url) throws IOException {
HttpURLConnection urlConnection = null;
String out = null;
try {
URL u = new URL(url);
urlConnection = (HttpURLConnection) u.openConnection();
urlConnection.setReadTimeout(TIME_OUT_LENGTH);
if (urlConnection.getResponseCode() != HTTP_STATUS_OK)
return null;
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
out = Connection.readStream(in);
} catch(IOException e) {
throw new IOException();
}
finally {
urlConnection.disconnect();
}
return out;
}
| public static String sendRequest(String url) throws IOException {
URL u = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
urlConnection.setReadTimeout(TIME_OUT_LENGTH);
if (urlConnection.getResponseCode() != HTTP_STATUS_OK)
throw new IOException();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String out = Connection.readStream(in);
urlConnection.disconnect();
return out;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.